<?php
namespace WXAPI\Controller;
use Api\Logic\GoodsLogic;
use Think\Page;
vendor('grafika.autoloader');
use Grafika\Color;
use Grafika\Grafika;
use Grafika\GrafikaHelper;
use Grafika\Curl;
class GoodsController extends BaseController {
    
    /**
     * 析构流函数
     */
	
    public function  __construct() {
        parent::__construct();
    } 
    
    public function index(){
       // $this->show('<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} body{ background: #fff; font-family: "微软雅黑"; color: #333;font-size:24px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.8em; font-size: 36px } a,a:hover,{color:blue;}</style><div style="padding: 24px 48px;"> <h1>:)</h1><p>欢迎使用 <b>ThinkPHP</b>！</p><br/>版本 V{$Think.version}</div><script type="text/javascript" src="http://ad.topthink.com/Public/static/client.js"></script><thinkad id="ad_55e75dfae343f5a1"></thinkad><script type="text/javascript" src="http://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script>','utf-8');
        $this->display();
    }

 //    public function cs(){
	// 	$goods=M('goods')->Field('goods_id,original_img')->select();
	// 	foreach($goods as $v){
	// 		M('goods_images')->where('image_url="'.$v['original_img'].'"')->delete();
	// 		//$aa=M('goods_images')->where('image_url="'.$v['original_img'].'"')->getField('image_url'); 
	// 		//echo $aa."<br/>";
	// 	}
	// }

    /**
     * 获取商品分类列表
     */
    public function goodsCategoryList(){
        $parent_id = I("parent_id",0);
        
		if($parent_id){
			$goodsCategoryList = M('GoodsCategory')->where("parent_id = $parent_id AND is_show=1")->order("is_hot desc,sort_order asc")->cache(true,TPSHOP_CACHE_TIME)->select();
		}else{
			$goodsCategoryList = M('GoodsCategory')->where("parent_id = $parent_id AND is_show=1 AND level=1")->order("is_hot desc,sort_order asc")->cache(true,TPSHOP_CACHE_TIME)->select();
		}
		
        //shadow code
        foreach ($goodsCategoryList as $key=>$value)
        {
            //$goodsCategoryList[$key]['image'] = SITE_URL.$value['image'];

			$zlist=M('GoodsCategory')->where("parent_id = ".$value['id']." AND is_show=1")->order("is_hot desc,sort_order asc")->cache(true,TPSHOP_CACHE_TIME)->select(); //三级分类
				foreach ($zlist as $keys=>$values)
				{
					//$zlist[$keys]['image'] = SITE_URL.$values['image'];
					//$zlist[$keys]['image'] = C('MYOSS')['url'].str_replace('/Public/', '', $values['image']);
					if($values['id'] > 4408){
					    $zlist[$keys]['image'] = C('MYOSS')['url'].$values['image'];
					}else{
        		    	if($values['id'] == 3947){
                             $zlist[$keys]['image'] = C('MYOSS')['url'].$values['image'];
                        }else{
                            $zlist[$keys]['image'] = C('MYOSS')['url2'].$values['image'];
                        }
                        
					}  
					
				}
			
			$goodsCategoryList[$key]['zlist'] = $zlist;
        }
			$brand=M('brand')->where("cat_id1 = ".$parent_id." and is_jie=1")->order("sort asc")->limit(9)->cache(true,TPSHOP_CACHE_TIME)->select(); //品牌对应
				foreach ($brand as $keys=>$values)
				{
					//$brand[$keys]['logo'] = SITE_URL.$values['logo'];
					//$brand[$keys]['logo'] = C('MYOSS')['url'].str_replace('/Public/', '', $values['logo']);
					$brand[$keys]['logo'] = C('MYOSS')['url'].$values['logo'];
				}
				
		
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$goodsCategoryList,'brand'=>$brand);
        $json_str = json_encode($json_arr);
        exit($json_str);
    }

    /**
     * 获取商品分类列表
     */
    public function categoryBanner(){
        $banner_name = $_GET['banner_name'];  //分类的名称
		$banner_name =	urldecode($banner_name);  //分类的名称
        $image =  M('goods_category')->where(array("name"=>$banner_name,"parent_id"=>0))->getField("image");
        $ad_names = M('Ad')->where(array('ad_name'=>"$banner_name"))->field('ad_name')->find();
        $ad_name = $ad_names['ad_name'];
        if (!empty($ad_name)){
            $image = M('Ad')->where(array('ad_name'=>"$ad_name"))->getField("ad_code");
        }else{
            $image = $image;
        }

        if ($image){
            $banner = array();
            //$banner['image'] = SITE_URL.$image;
			$banner['image'] = C('MYOSS')['url'].str_replace('/Public/', '', $image);
			$banner['image'] = C('MYOSS')['url'].$image;
            $json_arr = array('status'=>1,'msg'=>'获取成功',"banner"=>$banner);
            $json_str = json_encode($json_arr);
            exit($json_str);
        }
        $json_arr = array('status'=>0,'msg'=>'获取失败' );
        $json_str = json_encode($json_arr);
        exit($json_str);
    }
    
    /**
     * 获取产品须知
     * */
    public function goodsNotice(){
        $model = M('config');
        $model->where(array('inc_type'=>'basic','name'=>'goodsNotice'));
        $list = $model->find();
        if(!empty($list)){
            if(empty($list['value'])){
                $json_arr = array('status'=>0,'msg'=>'获取失败' );
                $json_str = json_encode($json_arr);
                exit($json_str);
            }
            if(!empty($list['value'])){
                $list['value'] = C('MYOSS')['url'].$list['value'];
            }
            $json_arr = array('status'=>1,'msg'=>'获取成功','data'=>$list);
        }else{
            $json_arr = array('status'=>0,'msg'=>'获取失败' );
        }
        $json_str = json_encode($json_arr);
        exit($json_str);
    }
        
    /*
    *商品导出
    */
    public function exclleGoods(){
        $cPage = I('p',0);
        $cPage = $cPage * 10;
        $store_id = I('store_id');
        
         $list = M('spec_goods_price a')
        ->field('g.goods_name,a.goods_id,s.store_name,b.name as bname,g.cat_id2,g.original_img,g.cat_id1,g.cat_id3,a.sku,a.key_name,a.price,a.qipi_num,a.spu,g.keywords')
        ->join('ty_goods g on g.goods_id = a.goods_id','LEFT')
        ->join('ty_store s on s.store_id = g.store_id','LEFT')
        ->join('ty_brand b on b.id = g.brand_id','LEFT')
        ->where(['g.is_on_sale'=>1,'g.goods_state'=>1,'g.store_id'=>$store_id])
        ->limit($cPage, 10)
        ->select();
        foreach ($list as $k=>$v){
            if(!empty($v['cat_id1'])){
                $cat_id1 = M('goods_category')->field('name')->where(['id'=>$v['cat_id1']])->find();
                $list[$k]['cat_id1'] = $cat_id1['name'];
            }
            if(!empty($v['cat_id2'])){
                $cat_id2 = M('goods_category')->field('name')->where(['id'=>$v['cat_id2']])->find();
                $list[$k]['cat_id2'] = $cat_id2['name'];
            }
            if(!empty($v['cat_id3'])){
                $cat_id3 = M('goods_category')->field('name')->where(['id'=>$v['cat_id3']])->find();
                $list[$k]['cat_id3'] = $cat_id3['name'];
            }
            $image = M('goods_images')->field('image_url')->where(['goods_id'=>$v['goods_id']])->limit(4)->select();
            if(!empty($image[0]['image_url'])){
               $list[$k]['image'] = 'https://yc.zczmer.com'.$image[0]['image_url']; 
            }else{
                $list[$k]['image'] = '';
            }
            if(!empty($image[1]['image_url'])){
               $list[$k]['image1'] = 'https://yc.zczmer.com'.$image[1]['image_url']; 
            }else{
                $list[$k]['image1'] = '';
            }
            if(!empty($image[2]['image_url'])){
               $list[$k]['image2'] = 'https://yc.zczmer.com'.$image[2]['image_url']; 
            }else{
                $list[$k]['image2'] = '';
            }
            if(!empty($image[3]['image_url'])){
               $list[$k]['image3'] = 'https://yc.zczmer.com'.$image[3]['image_url']; 
            }else{
                $list[$k]['image3'] = '';
            }
        }
       if(!empty($list)){
          $json_str = json_encode(['status'=>1,'data'=>$list,'msg'=>'获取成功'],true); 
       }else{
           $json_str = json_encode(['status'=>0,'data'=>$list,'msg'=>'获取成功'],true); 
       }
        
        exit($json_str);
    }
    /**
     * 获取根据一级分类获取对应的二三级分类
     */
    public function goodsSecAndThirdCategoryList(){
        $parent_id = I("parent_id",0); 
     // SELECT * FROM `tp_goods_category` WHERE parent_id_path LIKE '%0\_1\_%'
      /** 一次查询所有二级和三级分类  **/
        
        $test_str = 'POST'.print_r($_POST,true);
        $test_str .= 'GET'.print_r($_GET,true);
        file_put_contents('D:\temp\a.html', $test_str);
        
        $list = M('GoodsCategory')->where("parent_id_path LIKE '%0\\_{$parent_id}\\_%' AND is_show=1")->getField('id,mobile_name,image, level , parent_id');
        $list2 = array();
        foreach ($list as $k =>$v )
        {        
                if($v['level'] == 3)
                    continue;
                
                $arr = array();
                $arr['mobile_name'] = $v['mobile_name'];
                $arr['image'] = $v['image'];
                $arr['id'] = $v['id'];
                $arr['level'] = $v['level'];
                $arr['parent_id'] = $v['parent_id'];
                
                $arr3 = array();
                foreach ($list as $k2 => $v2){                
                    if($v['id'] == $v2['parent_id']){
                        $arr3['mobile_name'] = $v2['mobile_name'];
                        $arr3['image'] = $v2['image'];
                        $arr3['id'] = $v2['id'];
                        $arr3['level'] = $v2['level'];
                        $arr3['parent_id'] = $v2['parent_id'];
                       $arr['sub_category'][] = $arr3;
                    }
                }  
                //var_dump($arr3);
                
                $list2[] =$arr;
        } 
        
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$list2 );
        $json_str = json_encode($json_arr);
        exit($json_str);
    }
    
    
    /**
     * 商品列表页
     */
    public function goodsList(){
    	C('URL_MODEL',0); // 返回给手机app 生成路径格式 为 普通 index.php?=api&c=  最普通的路径格式
        
        $key = md5($_SERVER['REQUEST_URI'].$_POST['start_price'].'_'.$_POST['end_price']);
        $html = S($key);
        if(!empty($html)) {
            exit($html);
        }
        $is_activity = I('is_activity',''); // 活动
        $p = I('get.p',0); // 当前分类id
        $filter_param = array(); // 帅选数组                        
        $id = I('get.id',1); // 当前分类id 
        $brand_id = I('get.brand_id',0); 
		$user_id = I('get.uid',0); 
        $spec = I('get.spec',0); // 规格 
        $attr = I('get.attr',''); // 属性        
        $sort = I('get.sort'); // 排序
        $sort_asc = I('get.sort_asc'); // 排序
        $price = I('get.price',''); // 价钱
        $start_price = trim(I('post.start_price','0')); // 输入框价钱
        $end_price = trim(I('post.end_price','0')); // 输入框价钱        
    	if($start_price && $end_price) $price = $start_price.'-'.$end_price; // 如果输入框有价钱 则使用输入框的价钱   	 
    	$filter_param['id'] = $id; //加入帅选条件中
    	$brand_id  && ($filter_param['brand_id'] = $brand_id); //加入帅选条件中
    	$spec  && ($filter_param['spec'] = $spec); //加入帅选条件中
    	$attr  && ($filter_param['attr'] = $attr); //加入帅选条件中
    	$price  && ($filter_param['price'] = $price); //加入帅选条件中
         
        //  if(!empty($sort)){
        //      $sort = I('sort');
        //      $sortArr = "$sort $sort_asc";
        //  }else{
        //      $sort = 'sales_sum';
        //      $sort_asc = 'desc';
        //      $sortArr = ['sorts asc',$sort=>$sort_asc,'goods_id'];;
        //  }
         if(!empty($sort)){  
            $sortStatus = 2;
            $sortArr = [$sort=>$sort_asc];
            // array('sorts asc',$sort=>$sort_asc,'sales_sum')
        }else{
            $sortStatus = 1;
            $sort_asc = 'desc';
            $sort = 'sales_sum';
            $sortArr = ['sorts asc','sales_sum desc','goods_id desc'];
        }
         
         
    	$goodsLogic = new \Home\Logic\GoodsLogic(); // 前台商品操作逻辑类
    	// 分类菜单显示
    	$goodsCate = M('GoodsCategory')->where("id = $id")->find();// 当前分类
    	//($goodsCate['level'] == 1) && header('Location:'.U('Home/Channel/index',array('cat_id'=>$id))); //一级分类跳转至大分类馆
    	$cateArr = $goodsLogic->get_goods_cate($goodsCate);
    	
    	// 帅选 品牌 规格 属性 价格
    	$cat_id_arr = getCatGrandson ($id);
        $where = '';
        $fgwhere = ' and fg.fenbu_id = '.$this->fenbu_id;
        if(!empty($is_activity) && $is_activity !='false'){
           $time = time();
            $filter_goods_id = M('goods a')
    		->join('ty_store b on a.store_id=b.store_id')
    		->join('ty_prom_goods p on p.id=a.prom_id','LEFT')
    		->where("a.is_on_sale=1 and b.store_state=1 and a.is_delete=0 and a.goods_state=1 and a.cat_id3 in(".  implode(',', $cat_id_arr).") and (b.quyu_stop IS NULL or b.quyu_stop NOT LIKE '%\"$this->fenbu_id\"%') and p.start_time <".$time." and p.end_time >".$time." and a.prom_id!=0")->cache(true,TPSHOP_CACHE_TIME)->getField("goods_id",true);
        }else{
            if($this->independence == 2){
           $where = "a.is_on_sale=1 and a.is_delete=0 and a.goods_state=1 and a.cat_id3 in(".  implode(',', $cat_id_arr).") and (a.quyu_stop IS NULL or a.quyu_stop NOT LIKE '%\"$this->fenbu_id\"%') and (b.quyu_stop IS NULL or b.quyu_stop NOT LIKE '%\"$this->fenbu_id\"%') and b.fenbu_id = ".$this->fenbu_id;
           }else{
               $where = "a.is_on_sale=1 and a.is_delete=0 and a.goods_state=1 and a.cat_id3 in(".  implode(',', $cat_id_arr).") and (a.quyu_stop IS NULL or a.quyu_stop NOT LIKE '%\"$this->fenbu_id\"%') and (b.quyu_stop IS NULL or b.quyu_stop NOT LIKE '%\"$this->fenbu_id\"%')";
           }
        }
       
    	$filter_goods_id = M('goods a')
		->join('ty_store b on a.store_id=b.store_id')
		->where($where)->getField("goods_id",true);
       
    	// 过滤帅选的结果集里面找商品
    	if($brand_id || $price)// 品牌或者价格
    	{
    		$goods_id_1 = $goodsLogic->getGoodsIdByBrandPrice($brand_id,$price); // 根据 品牌 或者 价格范围 查找所有商品id
    		$filter_goods_id = array_intersect($filter_goods_id,$goods_id_1); // 获取多个帅选条件的结果 的交集
    	}
    	if($spec)// 规格
    	{
    		$goods_id_2 = $goodsLogic->getGoodsIdBySpec($spec); // 根据 规格 查找当所有商品id
    		$filter_goods_id = array_intersect($filter_goods_id,$goods_id_2); // 获取多个帅选条件的结果 的交集
    	}
    	if($attr)// 属性
    	{
    		$goods_id_3 = $goodsLogic->getGoodsIdByAttr($attr); // 根据 规格 查找当所有商品id
    		$filter_goods_id = array_intersect($filter_goods_id,$goods_id_3); // 获取多个帅选条件的结果 的交集
    	}
    	 
    	// $filter_menu  = $goodsLogic->get_filter_menu($filter_param,'goodsList'); // 获取显示的帅选菜单
    	// $filter_price = $goodsLogic->get_filter_price($filter_goods_id,$filter_param,'goodsList'); // 帅选的价格期间
    	   $filter_brand = $goodsLogic->get_filter_brand($filter_goods_id,$filter_param,'goodsList',1); // 获取指定分类下的帅选品牌
    	// $filter_spec  = $goodsLogic->get_filter_spec($filter_goods_id,$filter_param,'goodsList',1); // 获取指定分类下的帅选规格
    	// $filter_attr  = $goodsLogic->get_filter_attr($filter_goods_id,$filter_param,'goodsList',1); // 获取指定分类下的帅选属性

    	$count = count($filter_goods_id);
    	$page = new Page($count,16);
    	$page->firstRow = $p * $page->listRows;
		
    	if($count > 0)
    	{
    // 		$goods_list = M('goods')->field('goods_id,cat_id3,goods_sn,goods_name,shop_price,comment_count,original_img,sales_sum,store_id,on_time,prom_type,prom_id,floating,sorts,jifen_price')
    //             ->where("goods_id in (".  implode(',', $filter_goods_id).")  and  is_on_sale=1 and is_delete=0 and goods_state=1")
    //             ->order($sortArr)->limit($page->firstRow.','.$page->listRows)->select();
            if($sortStatus == 2){
    	        $goods_list = M('goods')
				->field('original_img,goods_id,cat_id3,goods_sn,goods_name,shop_price,prom_id,prom_type,comment_count,sales_sum,is_on_sale,is_delete,floating,sorts,store_id,jifen_price')
				->where("goods_id in (".  implode(',', $filter_goods_id).") and is_on_sale=1 and is_delete=0 and goods_state=1")
				->cache(true,TPSHOP_CACHE_TIME)
//                    ->order(array($sort=>$sort_asc))->limit($page->firstRow.','.$page->listRows)->select();
				->order($sortArr)->limit($page->firstRow.','.$page->listRows)->select();
    	    }else{
    	        $goods_listSort = [];
    	        $ids = '';
    	        $gwhere = '';
    	        $gids = '';
    	        //置顶分部产品
    	        if($this->fenbu_id != '0'){
    	            $goods_listSort = M('goods a')
    				->field('a.original_img,a.goods_id,a.cat_id3,a.goods_sn,a.goods_name,a.shop_price,a.prom_id,a.prom_type,a.comment_count,a.sales_sum,a.is_on_sale,a.is_delete,a.floating,a.store_id,a.jifen_price,fg.sorts as sorts,fg.sales_sum as fsales_sum')
    				->join('ty_fenbu_goods fg on fg.goods_id = a.goods_id','LEFT')
    				->cache(true,TPSHOP_CACHE_TIME)
    				->where("a.goods_id in (".  implode(',', $filter_goods_id).") and a.is_on_sale=1 and a.is_delete=0 and a.goods_state=1".$fgwhere)
    				->order(['fg.sorts asc','fg.sales_sum desc','a.goods_id desc'])->select();
    				if(!empty($goods_listSort)){
    				    foreach ($goods_listSort as $k=>$val){
    				        $ids .= $val['goods_id'].',';
    				        if(empty($val['sorts']) || empty($val['fsales_sum'])){
    				            $goodsInfo = M('goods')->field('sorts,sales_sum')->where(['goods_id'=>$val['goods_id']])->find();
    				            if(empty($val['sorts']) || $val['sorts'] == 0){
    				                $goods_listSort[$k]['sorts'] = $goodsInfo['sorts'];
    				            }
    				            if(empty($val['sales_sum']) || $val['fsales_sum'] == 0){
    				                $goods_listSort[$k]['sales_sum'] = $val['sales_sum']+$val['fsales_sum'];
    				            }
    				            
    				        }else{
    				            $goods_listSort[$k]['sales_sum'] = $val['sales_sum']+$val['fsales_sum'];
    				        }
        				}
        				$ids = substr($ids,0,-1);
        				$gwhere = " and goods_id NOT IN ($ids)";
    				}	
    				
    	        }
                $goods_list = M('goods')
				->field('original_img,goods_id,cat_id3,goods_sn,goods_name,shop_price,prom_id,prom_type,comment_count,sales_sum,is_on_sale,is_delete,floating,sorts,store_id,jifen_price')
				->where("goods_id in (".  implode(',', $filter_goods_id).") and is_on_sale=1 and is_delete=0 and goods_state=1 ".$gwhere)
				->cache(true,TPSHOP_CACHE_TIME)
//                    ->order(array($sort=>$sort_asc))->limit($page->firstRow.','.$page->listRows)->select();
				->order($sortArr)
				->select();
				    $goods_lists = array_merge($goods_listSort,$goods_list);
				    
				    // 按照age键值升序排序
                    // usort($goods_list, function($a, $b) {
                    //     return $b['sales_sum'] <=> $a['sales_sum'];
                    // });
                    // $list['goods_list2'] = $goods_list;
                    usort($goods_lists, function($a, $b) {
                        // 先按照 'sort' 键正序排序
                        if ($a['sorts'] == $b['sorts']) {
                            // 如果 'sort' 相同，则按照 'age' 键倒序排序
                            return $b['sales_sum'] - $a['sales_sum']; // 注意这里返回的是 $b - $a，以实现倒序
                        }
                        return $a['sorts'] - $b['sorts']; // 正序排序
                    });
                    // usort($goods_list, function($a, $b) {
                    //     $nameA = $a['sorts'];
                    //     $nameB = $b['sorts'];
                    //     if ($nameA == $nameB) {
                    //         return $a['sales_sum'] <=> $b['sales_sum'];
                    //     }
                    //     return $nameA <=> $nameB;
                    // });
                    // $list['goods_list3'] = $goods_list;
				    foreach ($goods_lists as $val){
    				    $gids .= $val['goods_id'].',';
    				}
    				if(!empty($gids)){
    				    $gids = substr($gids,0,-1);
    				}
    				
    				$goods_list = M('goods a')
				->field('a.original_img,a.goods_id,a.cat_id3,a.goods_sn,goods_name,a.shop_price,a.prom_id,prom_type,a.comment_count,a.sales_sum,a.is_on_sale,a.is_delete,a.floating,a.sorts,a.sort,a.store_id,a.jifen_price,a.stop_yijia,a.brand_id,a.store_cat_id1,a.prom_lock')
				->join('ty_store s on s.store_id = a.store_id')
				->where("a.goods_id in (".$gids.") ")
                ->order("FIELD(a.goods_id, ".$gids. ")")->cache(true,TPSHOP_CACHE_TIME)->limit($page->firstRow.','.$page->listRows)->select();
    	    }
    	    
    // 		$goods_list = M('goods')->field('goods_id,cat_id3,goods_sn,goods_name,shop_price,comment_count,original_img,sales_sum,store_id,on_time,prom_type,prom_id,floating,sorts,jifen_price')
    //         ->where("goods_id in (".  implode(',', $filter_goods_id).")  and  is_on_sale=1 and is_delete=0 and goods_state=1")
    //         ->order($sortArr)->limit($page->firstRow.','.$page->listRows)->select();
				// dump($goods_list);
    		$filter_goods_id2 = get_arr_column($goods_list, 'goods_id');
    		
    	}
		//echo \json_encode($goods_list);exit;
    	$goods_category = M('goods_category')->where('is_show=1')->getField('id,name,parent_id,level'); // 键值分类数组
    	$fast_flag = M('users')->where("user_id=".$this->user_id)->cache(true,TPSHOP_CACHE_TIME)->getField('fast_flag');
    	if ($user_id) {
            $user = M('users')->where("user_id = {$this->user_id}")->cache(true,TPSHOP_CACHE_TIME)->find();
			$discount=$user['discount'];
        }
        
// 		if($discount){
// 			$goods['shop_price']=$discount*$goods['shop_price'];
// 		}
        $time = time();
    	foreach ($goods_list as $key=>$value)
    	{ 
    		if($discount){
			    $value['shop_price']=$discount*$value['shop_price'];
		    }
    		//$goods_list[$key]['image'] = SITE_URL.$value['original_img'];
			//$goods_list[$key]['image'] = C('MYOSS')['url'].str_replace('/Public/', '', $value['original_img']);
			$quyu_price=quyu_price($this->fenbu_id,$value['store_id'],$value['goods_id']);
			$goods_list[$key]['image'] = C('MYOSS')['url'].$value['original_img'];
            $float = check_float($value['store_id'],$this->user_id,$value['goods_id']);
            $value['floating'] = $value['floating']+$float;
			$goods_list[$key]['shop_price']= geshi($value['shop_price']*$value['floating']/100*$quyu_price);//浮点计算
            $yj_h1 = yj_h1($value['goods_id'],$goods_list[$key]['shop_price'],$this->fenbu_id);
            if($value['stop_yijia'] == 1){
                $goods_list[$key]['shop_price'] += yj_price($value['goods_id'],$goods_list[$key]['shop_price'],$this->fenbu_id);
            }
			

            //查询是否快线店铺
            $store = M('store')->where(['store_id'=>$value['store_id']])->find();
            if ($store['fast_flag'] && $fast_flag == 1){
                $goods_list[$key]['fast_text'] = '快线';
            }
            
            //判断是否有满赠活动
            $goodsFull = M('goods_full')->where("store_id = ".$value['store_id']." and start_time <=$time and end_time >=$time")->order('id desc')->find();
            if(!empty($goodsFull) && $value['prom_lock'] == 0){
                if(!empty($goodsFull['brand_id'])){
                    $brand_id = json_decode($goodsFull['brand_id'],true);
                    if(in_array($value['store_cat_id1'],$brand_id)){
                        $goods_list[$key]['full_status'] = 1;
                        $goods_list[$key]['full_text'] = '店铺满赠';
                    }else{
                        $goods_list[$key]['full_status'] = 0;
                        $goods_list[$key]['full_text'] = '';
                    }
                }elseif(!empty($goodsFull['goods_id'])){
                    $goods_id = json_decode($goodsFull['goods_id'],true);
                    if(in_array($value['goods_id'],$goods_id)){
                        $goods_list[$key]['full_status'] = 1;
                        $goods_list[$key]['full_text'] = '店铺满赠';
                    }else{
                        $goods_list[$key]['full_status'] = 0;
                        $goods_list[$key]['full_text'] = '';
                    }
                }else{
                    $goods_list[$key]['full_status'] = 1;
                    $goods_list[$key]['full_text'] = '店铺满赠';
                }
            }else{
                $goods_list[$key]['full_status'] = 0;
                $goods_list[$key]['full_text'] = '';
            }
            
            $goods_list[$key]['shop_price'] = geshi($goods_list[$key]['shop_price']);
			if($this->user_id==61)
			$goods_list[$key]['shop_price']='登陆查看'; //浮点计算
			$goods_list[$key]['status_status']=0;
                // 商品分类页优惠折扣显示 20181129 亮 START
                if (($value['prom_id']>0) && $value['prom_id']){
                    $prom_goods = M('prom_goods')->where(array('id'=>$value['prom_id']))->find();
                    //$prom_code = SITE_URL.$prom_goods['prom_code'];
					//$prom_code = C('MYOSS')['url'].str_replace('/Public/', '', $prom_goods['prom_code']);
					$prom_code = C('MYOSS')['url'].$prom_goods['prom_code'];
                    
                    $datass = time();
                    if (($datass > $prom_goods['start_time']) && ($datass < $prom_goods['end_time'])){
                        $prom_key = json_decode($prom_goods['goods_key'],true);
                
                        if($value['zd']!=1 && $prom_key){
                            $spec_goods_price_list  = M('spec_goods_price')->where(['key'=>['in',implode(',',$prom_key)],'goods_id'=>$value['goods_id']])->select();
                            usort($spec_goods_price_list, function($a, $b) {
                                // 先按照 'sort' 键正序排序
                                return $a['price'] - $b['price']; // 正序排序
                            });
                        }
                        if(!empty($spec_goods_price_list[0]['price'])){
                            $goods_list[$key]['shop_price'] = $spec_goods_price_list[0]['price'];
                        }
						$statusss = 1;
                        if ($prom_goods['type'] == 0){
                            $prom_goods_price = geshi($goods_list[$key]['shop_price'] * ($prom_goods['expression'] / 100)); //活动折扣
                            $prom_goods_content = 0;
                            if($yj_h1 < 0 && $value['stop_yijia'] == 1){
                                $yj_h1 = $yj_h1*100;
                                $prom_goods['expression'] = $prom_goods['expression']+$yj_h1;
                            }
                        }elseif($prom_goods['type'] == 1){
                            $prom_goods_price = $goods_list[$key]['shop_price'] - $prom_goods['expression'];
                            $prom_goods_content = 0; 
                        }elseif($prom_goods['type'] == 2){
                            $prom_goods_price = $prom_goods['expression'];
                            $prom_goods_content = 0;
                        }elseif($prom_goods['type'] == 5){
                            $prom_goods_price = geshi($goods_list[$key]['shop_price'] * ($prom_goods['expression'] / 100)); //活动折扣
                            $prom_goods_content = 0;
                            if($yj_h1 < 0 && $value['stop_yijia'] == 1){
                                $yj_h1 = $yj_h1*100;
                                $prom_goods['expression'] = $prom_goods['expression']+$yj_h1;
                            }
                        }else{
                            $prom_goods_price = $goods_list[$key]['shop_price'];
                            $prom_goods_content = "购买赠送代金券$prom_goods[expression]元";
                        }
						$goods_list[$key]['expression'] =$prom_goods['expression'];
						$goods_list[$key]['expressions'] =huodong_name($prom_goods['type'],$prom_goods['expression']);
						$goods_list[$key]['prom_goods_price'] = \sanwei($prom_goods_price);
//                        $goods_list[$key]['prom_goods_price']= $user_id=='61'?'登陆查看':\sanwei($goods_list[$key]['shop_price']);
						$goods_list[$key]['prom_goods_content'] = $prom_goods_content;
						$goods_list[$key]['prom_code'] = $prom_code;
						$goods_list[$key]['status_status'] = $statusss;
                    }
                }
                
    	}
		
		$list['goods_list'] = $goods_list;
		
        $i = 1;
    	//菜单
        foreach($filter_menu as $k => $v) // 依照app端的要求 去掉 键名
        {
            $v['name'] = $v['text'];
            unset($v['text']);
            $list['filter_menu'][] = $v;  // 帅选规格
        }
        
        // 规格
        foreach($filter_spec as $k => $v) // 依照app端的要求 去掉 键名
        {   
             $items['name'] = $v['name'];
             foreach($v['item'] as $k2 => $v2)
             {
                 $items['item'][] = array('name'=>$v2['item'],'href'=>$v2['href'],'id'=>$i++);
             }
            $list['filter_spec'][] = $items;
            $items = array();
        }
        
        // $list['filter_spec'] = $filter_spec;
        // 属性
        foreach($filter_attr as $k => $v) // 依照app端的要求 去掉 键名
        {           
            $items['name'] = $v['attr_name'];
             foreach($v['attr_value'] as $k2 => $v2)
             {
                $items['item'][] = array('name'=>$v2['attr_value'],'href'=>$v2['href'],'id'=>$i++);
             }
           
            $list['filter_attr'][] = $items;
            $items = array();
        }                
        // 品牌
        foreach($filter_brand as $k => $v) // 依照app端的要求 去掉 键名
        {                                              
            $list['filter_brand'][] = array('name'=>$v['name'],'href'=>$v['href'],'brand_id'=>$v['brand_id'],'id'=>$i++);
        }        
                    
        // 价格
        foreach($filter_price as $k => $v) // 依照app端的要求 去掉 键名
        {                                              
            $list['filter_price'][] = array('name'=>$v['value'],'href'=>$v['href'],'id'=>$i++);
        }
        

        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$list );
        $json_str = json_encode($json_arr,true);            
        exit($json_str);
    }    
    public function search(){
        C('URL_MODEL',0); // 返回给手机app 生成路径格式 为 普通 index.php?=api&c=  最普通的路径格式
    	$p = I('get.p',0);
    	$id = I('get.id',0); // 当前分类id
    	$brand_id = I('brand_id',0);
        $sort = I('sort'); // 排序
        $sort_asc = I('sort_asc'); // 排序
    	$price = I('price',''); // 价钱
    	$cat_id1 = I('cat_id1',''); // 价钱
    	$is_activity = I('is_activity',''); // 价钱
        $fgwhere = ' and fg.fenbu_id = '.$this->fenbu_id;
        
        if(!empty($sort)){  
            $sortStatus = 2;
            $sortArr = [$sort=>$sort_asc];
            // array('sorts asc',$sort=>$sort_asc,'sales_sum')
        }else{
            $sortStatus = 1;
            $sort_asc = 'desc';
            $sort = 'sales_sum';
            $sortArr = ['sorts asc','sales_sum desc','goods_id desc'];
        }
      
        // if(!empty($sort_asc)){
        //     $sort = I('sort_asc');   
        // }else{
        //     $sort = 'desc';
        // }
        
    	$start_price = trim(I('start_price','0')); // 输入框价钱
    	$end_price = trim(I('end_price','0')); // 输入框价钱
    	if($start_price && $end_price) $price = $start_price.'-'.$end_price; // 如果输入框有价钱 则使用输入框的价钱   	 

    	$filter_param['id'] = $id; //加入帅选条件中
    	$brand_id  && ($filter_param['brand_id'] = $brand_id); //加入帅选条件中  
    	$price  && ($filter_param['price'] = $price); //加入帅选条件中
//echo $brand_id;exit;
        $more_list = urldecode(trim(I('more_list',''))); // 关键字搜索
		$q = urldecode(trim(I('keywords',''))); // 关键字搜索
		$user_id = $this->user_id; // 关键字搜索
		//echo $user_id;exit;
        $q  && ($_GET['q'] = $filter_param['q'] = $q); //加入帅选条件中

        //     exit(json_encode(array('status'=>-1,'msg'=>'请输入搜索关键词'),true));
       if($this->independence == 2){
           $andwhere=" a.is_on_sale=1 and a.is_delete=0 and a.goods_state=1 and (a.quyu_stop IS NULL or a.quyu_stop NOT LIKE '%\"$this->fenbu_id\"%') and (b.quyu_stop IS NULL or b.quyu_stop NOT LIKE '%\"$this->fenbu_id\"%') and b.store_state=1 and and prom_id != 101 and b.fenbu_id = ".$this->fenbu_id; //默认条件
       }else{
           $andwhere=" a.is_on_sale=1 and a.is_delete=0 and a.goods_state=1 and (a.quyu_stop IS NULL or a.quyu_stop NOT LIKE '%\"$this->fenbu_id\"%') and prom_id != 101 and (b.quyu_stop IS NULL or b.quyu_stop NOT LIKE '%\"$this->fenbu_id\"%') and b.store_state=1"; //默认条件
       }
       if(!empty($cat_id1)){
            $andwhere .= ' and a.cat_id1 = '.$cat_id1;
        }
    	$goodsLogic = new \Home\Logic\GoodsLogic(); // 前台商品操作逻辑类
		if($brand_id){
            if($q){
                $filter_goods_id = M('goods a')
                    ->join('ty_store b on a.store_id=b.store_id')
                    ->where("a.brand_id=".$brand_id." and (goods_name like '%{$q}%' or keywords like '%{$q}%') and ".$andwhere)->cache(true,TPSHOP_CACHE_TIME)->getField("goods_id",true);
            }else{
                $filter_goods_id = M('goods a')
                    ->join('ty_store b on a.store_id=b.store_id')
                    ->where("a.brand_id=".$brand_id." and ".$andwhere)->cache(true,TPSHOP_CACHE_TIME)->getField("goods_id",true);
            }

		}elseif($more_list){
			$filter_goods_id = M('goods a')
			->join('ty_store b on a.store_id=b.store_id')
			->where($more_list."=1 and ".$andwhere)->cache(true,TPSHOP_CACHE_TIME)->getField("goods_id",true);
		}else{
			$filter_goods_id = M('goods a')
			->join('ty_store b on a.store_id=b.store_id')
			->where($andwhere." and (goods_name like '%{$q}%' or keywords like '%{$q}%')")->cache(true,TPSHOP_CACHE_TIME)->getField("goods_id",true);
	       
			
			//判断记录关键词
			if($q && $filter_goods_id){
				$pds=M('user_record')->where("user_id=".$user_id." and `keyword`='".$q."'")->order('id desc')->cache(true,TPSHOP_CACHE_TIME)->getField('click');
				if(empty($pds)){
					$clicks=50;
					$pdscount=M('user_record')->where("user_id=".$user_id)->count();
					if($pdscount>50)
						M('user_record')->where("user_id=".$user_id)->order('id asc')->limit('5')->delete();
				}else{
					$clicks=$pds+1;
					M('user_record')->where("user_id=".$user_id." and `keyword`='".$q."'")->delete();
				}
					 M('user_record')->add([
						 'keyword'=>$q,
						 'user_id'=>$user_id,
						 'click'=>$clicks
					 ]);
			}
		}
	    if(!empty($is_activity) && $is_activity!='false'){
		    $time = time();
		    $activitywhere = 'p.start_time <'.$time.' and p.end_time >'.$time.' and a.prom_id!=0';
		    $filter_goods_id = M('goods a')
			->join('ty_store b on a.store_id=b.store_id')
			->join('ty_prom_goods p on p.id=a.prom_id')
			->where($activitywhere." and a.goods_id in (".  implode(',', $filter_goods_id).")")->cache(true,TPSHOP_CACHE_TIME)->getField("goods_id",true);
		}
    	// 过滤帅选的结果集里面找商品
//    	if($brand_id || $price)// 品牌或者价格
//    	{
//    		$goods_id_1 = $goodsLogic->getGoodsIdByBrandPrice($brand_id,$price); // 根据 品牌 或者 价格范围 查找所有商品id
//    		$filter_goods_id = array_intersect($filter_goods_id,$goods_id_1); // 获取多个帅选条件的结果 的交集
//    	}

    	$filter_menu  = $goodsLogic->get_filter_menu($filter_param,'search'); // 获取显示的帅选菜单
    	$filter_price = $goodsLogic->get_filter_price($filter_goods_id,$filter_param,'search'); // 帅选的价格期间
		
    	$filter_brand = $goodsLogic->get_filter_brand($filter_goods_id,$filter_param,'search',1); // 获取指定分类下的帅选品牌    	 
    	
    	$count = count($filter_goods_id);
    	$page = new Page($count,16);
    	$page->firstRow = $p * $page->listRows;
    	 if ($user_id) {
            $user = M('users')->where("user_id = {$user_id}")->cache(true,TPSHOP_CACHE_TIME)->find();
			$discount=$user['discount'];
        }
    	if($count > 0)
    	{       
    	    
    	    if($sortStatus == 2){
    	        $goods_list = M('goods')
				->field('original_img,goods_id,cat_id3,goods_sn,goods_name,shop_price,prom_id,prom_type,comment_count,sales_sum,is_on_sale,is_delete,floating,sorts,store_id,jifen_price')
				->where("goods_id in (".  implode(',', $filter_goods_id).") and is_on_sale=1 and is_delete=0 and goods_state=1")
				->cache(true,TPSHOP_CACHE_TIME)
//                    ->order(array($sort=>$sort_asc))->limit($page->firstRow.','.$page->listRows)->select();
				->order($sortArr)->limit($page->firstRow.','.$page->listRows)->select();
    	    }else{
    	        $goods_listSort = [];
    	        $ids = '';
    	        $gwhere = '';
    	        $gids = '';
    	        //置顶分部产品
    	        if($this->fenbu_id != '0'){
    	            $goods_listSort = M('goods a')
    				->field('a.original_img,a.goods_id,a.cat_id3,a.goods_sn,a.goods_name,a.shop_price,a.prom_id,a.prom_type,a.comment_count,a.sales_sum,a.is_on_sale,a.is_delete,a.floating,a.store_id,a.jifen_price,fg.sorts as sorts,fg.sales_sum as fsales_sum')
    				->join('ty_fenbu_goods fg on fg.goods_id = a.goods_id','LEFT')
    				->where("a.goods_id in (".  implode(',', $filter_goods_id).") and a.is_on_sale=1 and a.is_delete=0 and a.goods_state=1".$fgwhere)
    				->cache(true,TPSHOP_CACHE_TIME)
    				->order(['fg.sorts asc','fg.sales_sum desc','a.goods_id desc'])->group('a.goods_id')->select();
    				
    				if(!empty($goods_listSort)){
    				    foreach ($goods_listSort as $k=>$val){
    				        $ids .= $val['goods_id'].',';
    				        if(empty($val['sorts']) || empty($val['fsales_sum'])){
    				            $goodsInfo = M('goods')->field('sorts,sales_sum')->where(['goods_id'=>$val['goods_id']])->find();
    				            if(empty($val['sorts']) || $val['sorts'] == 0){
    				                $goods_listSort[$k]['sorts'] = $goodsInfo['sorts'];
    				            }
    				            if(empty($val['fsales_sum'])){
    				                $goods_listSort[$k]['sales_sum'] = $goodsInfo['sales_sum']+$val['fsales_sum'];
    				            }
    				            
    				        }else{
    				             $goods_listSort[$k]['sales_sum'] = $val['sales_sum']+$val['fsales_sum'];
    				        }
    				        
        				}
        				$ids = substr($ids,0,-1);
        				$gwhere = " and goods_id NOT IN (".$ids.")";
    				}	
    				
    	        }
    	        
                $goods_list = M('goods')
				->field('original_img,goods_id,cat_id3,goods_sn,goods_name,shop_price,prom_id,prom_type,comment_count,sales_sum,is_on_sale,is_delete,floating,sorts,store_id,jifen_price')
				->where("goods_id in (".  implode(',', $filter_goods_id).") and is_on_sale=1 and is_delete=0 and goods_state=1 ".$gwhere)
//                    ->order(array($sort=>$sort_asc))->limit($page->firstRow.','.$page->listRows)->select();
				->order($sortArr)
				->cache(true,TPSHOP_CACHE_TIME)
				->select();
				    $goods_list = array_merge($goods_listSort,$goods_list);
				    // 按照age键值升序排序
                    // usort($goods_list, function($a, $b) {
                    //     return $b['sales_sum'] <=> $a['sales_sum'];
                    // });
                    // $list['goods_list2'] = $goods_list;
                    usort($goods_list, function($a, $b) {
                        // 先按照 'sort' 键正序排序
                        if ($a['sorts'] == $b['sorts']) {
                            // 如果 'sort' 相同，则按照 'age' 键倒序排序
                            return $b['sales_sum'] - $a['sales_sum']; // 注意这里返回的是 $b - $a，以实现倒序
                        }
                        return $a['sorts'] - $b['sorts']; // 正序排序
                    });
                    // usort($goods_list, function($a, $b) {
                    //     $nameA = $a['sorts'];
                    //     $nameB = $b['sorts'];
                    //     if ($nameA == $nameB) {
                    //         return $a['sales_sum'] <=> $b['sales_sum'];
                    //     }
                    //     return $nameA <=> $nameB;
                    // });
                    // $list['goods_list3'] = $goods_list;
				    foreach ($goods_list as $val){
    				    $gids .= $val['goods_id'].',';
    				}
    				if(!empty($gids)){
    				    $gids = substr($gids,0,-1);
    				}
    				
    				$goods_list = M('goods a')
				->field('a.original_img,a.goods_id,a.cat_id3,a.goods_sn,goods_name,a.shop_price,a.prom_id,prom_type,a.comment_count,a.sales_sum,a.is_on_sale,a.is_delete,a.floating,a.sorts,a.sort,a.store_id,a.jifen_price,a.stop_yijia,a.brand_id,a.store_cat_id1,a.prom_lock')
				->join('ty_store s on s.store_id = a.store_id')
				->where("a.goods_id in (".$gids.") ")
                ->order("FIELD(a.goods_id, ".$gids. ")")->limit($page->firstRow.','.$page->listRows)->cache(true,TPSHOP_CACHE_TIME)->select();
    	    }
    	        
				// dump($goods_list);
    		$filter_goods_id2 = get_arr_column($goods_list, 'goods_id');
    	}
 
    	$goods_category = M('goods_category')->where('is_show=1')->getField('id,name,parent_id,level'); // 键值分类数组
    	$fast_flag = M('users')->where("user_id=".$user_id)->cache(true,TPSHOP_CACHE_TIME)->getField('fast_flag');
    	$time = time();
    	foreach ($goods_list as $key=>$value)
    	{
    	    if($discount){
    			$value['shop_price']=$discount*$value['shop_price'];
    		}
			$quyu_price=quyu_price($this->fenbu_id,$value['store_id']);
			$goods_list[$key]['image'] = C('MYOSS')['url'].$value['original_img'];

            $float = check_float($value['store_id'],$this->user_id,$value['goods_id']);
            $value['floating'] = $value['floating']+$float;

			$goods_list[$key]['shop_price'] = geshi($value['shop_price']*($value['floating']/100)*$quyu_price);//浮点计算
            if($value['stop_yijia'] == 1){
                $goods_list[$key]['shop_price'] +=yj_price($value['goods_id'],$goods_list[$key]['shop_price'],$this->fenbu_id);
            }
            //判断是否有满赠活动
            $goodsFull = M('goods_full')->where("store_id = ".$value['store_id']." and start_time <=$time and end_time >=$time")->order('id desc')->find();
            if(!empty($goodsFull) && $value['prom_lock'] == 0){
                if(!empty($goodsFull['brand_id'])){
                    $brand_id = json_decode($goodsFull['brand_id'],true);
                    if(in_array($value['store_cat_id1'],$brand_id)){
                        $goods_list[$key]['full_status'] = 1;
                        $goods_list[$key]['full_text'] = '店铺满赠';
                    }else{
                        $goods_list[$key]['full_status'] = 0;
                        $goods_list[$key]['full_text'] = '';
                    }
                }elseif(!empty($goodsFull['goods_id'])){
                    $goods_id = json_decode($goodsFull['goods_id'],true);
                    if(in_array($value['goods_id'],$goods_id)){
                        $goods_list[$key]['full_status'] = 1;
                        $goods_list[$key]['full_text'] = '店铺满赠';
                    }else{
                        $goods_list[$key]['full_status'] = 0;
                        $goods_list[$key]['full_text'] = '';
                    }
                }else{
                    $goods_list[$key]['full_status'] = 1;
                    $goods_list[$key]['full_text'] = '店铺满赠';
                }
            }else{
                $goods_list[$key]['full_status'] = 0;
                $goods_list[$key]['full_text'] = '';
            }
			
			
            $yj_h1 = yj_h1($value['goods_id'],$goods_list[$key]['shop_price'],$this->fenbu_id);
            
            $goods_list[$key]['shop_price'] = geshi($goods_list[$key]['shop_price']);
			$goods_list[$key]['status_status']=0;
            //查询是否快线店铺
            $store = M('store')->where(['store_id'=>$value['store_id']])->find();
            if ($store['fast_flag'] && $fast_flag == 1){
                $goods_list[$key]['fast_text'] = '快线';
            }
                // 商品分类页优惠折扣显示 20181129 亮 START
                if (($value['prom_id'] >0) && $value['prom_id']){
                    $prom_goods = M('prom_goods')->where(array('id'=>$value['prom_id']))->find();
					$prom_code = C('MYOSS')['url'].$prom_goods['prom_code'];
                    
                    $prom_key = json_decode($prom_goods['goods_key'],true);
            
                    if($value['zd']!=1){
                        $spec_goods_price_list  = M('spec_goods_price')->where(['key'=>['in',implode(',',$prom_key)],'goods_id'=>$value['goods_id']])->select();
                        usort($spec_goods_price_list, function($a, $b) {
                            // 先按照 'sort' 键正序排序
                            return $a['price'] - $b['price']; // 正序排序
                        });
                    }
                    if(!empty($spec_goods_price_list[0]['price'])){
                        $goods_list[$key]['shop_price'] = $spec_goods_price_list[0]['price'];
                    }
                    
                    
                    $datass = time();
                    if (($datass > $prom_goods['start_time']) && ($datass < $prom_goods['end_time'])){
						$statusss = 1;
                        if ($prom_goods['type'] == 0){
                            $prom_goods_price = geshi($goods_list[$key]['shop_price'] * ($prom_goods['expression'] / 100)); //活动折扣
                            $prom_goods_content = 0;
                            if($yj_h1 < 0 && $value['stop_yijia'] == 1){
                                $yj_h1 = $yj_h1*100;
                                $prom_goods['expression'] = $prom_goods['expression']+$yj_h1;
                            }
                        }elseif($prom_goods['type'] == 1){
                            $prom_goods_price = $goods_list[$key]['shop_price'] - $prom_goods['expression'];
                            $prom_goods_content = 0; 
                        }elseif($prom_goods['type'] == 2){
                            $prom_goods_price = $prom_goods['expression'];
                            $prom_goods_content = 0;
                        }elseif($prom_goods['type'] == 5){
                             $prom_goods_price = geshi($goods_list[$key]['shop_price'] * ($prom_goods['expression'] / 100)); //活动折扣
                            $prom_goods_content = 0;
                            if($yj_h1 < 0 && $value['stop_yijia'] == 1){
                                $yj_h1 = $yj_h1*100;
                                $prom_goods['expression'] = $prom_goods['expression']+$yj_h1;
                            }
                        }else{
                            $prom_goods_price = $goods_list[$key]['shop_price'];
                            $prom_goods_content = "购买赠送代金券$prom_goods[expression]元";
                        }
						$goods_list[$key]['expression'] =$prom_goods['expression'];
						$goods_list[$key]['expressions'] =huodong_name($prom_goods['type'],$prom_goods['expression']);//'活动！'.str_replace("0","",$prom_goods['expression']).'折';
						$goods_list[$key]['prom_goods_price'] = $prom_goods_price;
						$goods_list[$key]['prom_goods_content'] = $prom_goods_content;
						$goods_list[$key]['prom_code'] = $prom_code;
						$goods_list[$key]['status_status'] = $statusss;
                    }
                }
    //             else{
    //                 if($yj_h1 < 0 && $value['stop_yijia'] == 1){
    //                     $yj_h1 = $yj_h1*100;
    //                     // $prom_goods['expression'] = $prom_goods['expression']+$yj_h1;
    //                     $goods_list[$key]['expression'] =100+$yj_h1;
				// 		$goods_list[$key]['expressions'] =huodong_name(0,$goods_list[$key]['expression']);//'活动！'.str_replace("0","",$prom_goods['expression']).'折';
				// 		$goods_list[$key]['prom_goods_price'] = $goods_list[$key]['shop_price'];
				// 		$goods_list[$key]['prom_goods_content'] = 0;
				// 		$goods_list[$key]['prom_code'] = $prom_code;
				// 		$goods_list[$key]['status_status'] = 1;
    //                 }
    //             }

				if($user_id=='61')
				$goods_list[$key]['shop_price']='登陆查看'; //浮点计算
    	}
    	
    	$list['goods_list'] = $goods_list;
        $i = 1;
    	//菜单
        foreach($filter_menu as $k => $v) // 依照app端的要求 去掉 键名
        {
            $v['name'] = $v['text'];
            unset($v['text']);
            $list['filter_menu'][] = $v;  // 帅选规格
        }
       
        // 品牌
        foreach($filter_brand as $k => $v) // 依照app端的要求 去掉 键名
        {
            $list['filter_brand'][] = array('name'=>$v['name'],'href'=>$v['href'],'brand_id'=>$v['brand_id'],'id'=>$i++);
        }

        // 价格
        foreach($filter_price as $k => $v) // 依照app端的要求 去掉 键名
        {
            $list['filter_price'][] = array('name'=>$v['value'],'href'=>$v['href'],'id'=>$i++);
        }
        
        $list['sort_asc'] =  $sortArr;
        $list['sort'] =  $sort;
        $list['orderby_default'] = urldecode(U("Goods/search",$filter_param,'')); // 默认排序
        $list['orderby_sales_sum'] = urldecode(U("Goods/search",array_merge($filter_param,array('sort'=>'sales_sum','sort_asc'=>'desc')),'')); // 销量排序
        $list['orderby_price'] = urldecode(U("Goods/search",array_merge($filter_param,array('sort'=>'shop_price','sort_asc'=>$sort_asc)),'')); // 价格
        $list['orderby_comment_count'] = urldecode(U("Goods/search",array_merge($filter_param,array('sort'=>'comment_count','sort_asc'=>'desc')),'')); // 评论
        $list['orderby_is_new'] = urldecode(U("Goods/search",array_merge($filter_param,array('sort'=>'is_new','sort_asc'=>'desc')),'')); // 新品
    	C('TOKEN_ON',false); //echo $list['goods_list'][0]['shop_price'];
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$list );

        $json_str = json_encode($json_arr,true);
        exit($json_str);
    }
	
     /**
     * 商品搜索列表页 
     */
    public function searchsss(){
        C('URL_MODEL',0); // 返回给手机app 生成路径格式 为 普通 index.php?=api&c=  最普通的路径格式
    	$p = I('get.p',0);
    	$id = I('get.id',0); // 当前分类id
    	$brand_id = I('brand_id',0);
        $sort = I('sort'); // 排序
        $sort_asc = I('sort_asc'); // 排序
    	$price = I('price',''); // 价钱
    	$is_activity = I('is_activity',''); // 价钱
        
        if(!empty($sort)){  
            $sortArr = [$sort=>$sort_asc];
            // array('sorts asc',$sort=>$sort_asc,'sales_sum')
        }else{
            $sort_asc = 'desc';
            $sort = 'sales_sum';
            $sortArr = ['sorts asc','sales_sum desc','goods_id desc'];
        }
        if(!empty($sort_asc)){
            $sort = I('sort_asc');   
        }else{
            $sort = 'desc';
        }
        

    	$start_price = trim(I('start_price','0')); // 输入框价钱
    	$end_price = trim(I('end_price','0')); // 输入框价钱
    	if($start_price && $end_price) $price = $start_price.'-'.$end_price; // 如果输入框有价钱 则使用输入框的价钱   	 

    	$filter_param['id'] = $id; //加入帅选条件中
    	$brand_id  && ($filter_param['brand_id'] = $brand_id); //加入帅选条件中  
    	$price  && ($filter_param['price'] = $price); //加入帅选条件中
//echo $brand_id;exit;
        $more_list = urldecode(trim(I('more_list',''))); // 关键字搜索
		$q = urldecode(trim(I('keywords',''))); // 关键字搜索
		$user_id = $this->user_id; // 关键字搜索
		//echo $user_id;exit;
        $q  && ($_GET['q'] = $filter_param['q'] = $q); //加入帅选条件中

        //     exit(json_encode(array('status'=>-1,'msg'=>'请输入搜索关键词'),true));
       if($this->independence == 2){
           $andwhere=' a.is_on_sale=1 and a.is_delete=0 and a.goods_state=1 and (INSTR(a.quyu_stop,"\"'.$this->fenbu_id.'\"")=0 or (a.quyu_stop is NULL or a.quyu_stop is null  )) and (INSTR(b.quyu_stop,"\"'.$this->fenbu_id.'\"")=0  or (b.quyu_stop is NULL or b.quyu_stop is null )) and b.store_state=1 and and prom_id != 101 and b.fenbu_id = '.$this->fenbu_id; //默认条件
       }else{
           $andwhere=' a.is_on_sale=1 and a.is_delete=0 and a.goods_state=1 and (INSTR(a.quyu_stop,"\"'.$this->fenbu_id.'\"")=0 or (a.quyu_stop is NULL or a.quyu_stop is null  )) and prom_id != 101 and (INSTR(b.quyu_stop,"\"'.$this->fenbu_id.'\"")=0  or (b.quyu_stop is NULL or b.quyu_stop is null )) and b.store_state=1'; //默认条件
       }
    	$goodsLogic = new \Home\Logic\GoodsLogic(); // 前台商品操作逻辑类
		if($brand_id){
            if($q){
                $filter_goods_id = M('goods a')
                    ->join('ty_store b on a.store_id=b.store_id')
                    ->where("a.brand_id=".$brand_id." and (goods_name like '%{$q}%' or keywords like '%{$q}%') and ".$andwhere)->cache(true,TPSHOP_CACHE_TIME)->getField("goods_id",true);
            }else{
                $filter_goods_id = M('goods a')
                    ->join('ty_store b on a.store_id=b.store_id')
                    ->where("a.brand_id=".$brand_id." and ".$andwhere)->cache(true,TPSHOP_CACHE_TIME)->getField("goods_id",true);
            }

		}elseif($more_list){
			$filter_goods_id = M('goods a')
			->join('ty_store b on a.store_id=b.store_id')
			->where($more_list."=1 and ".$andwhere)->cache(true,TPSHOP_CACHE_TIME)->getField("goods_id",true);
		}else{
			$filter_goods_id = M('goods a')
			->join('ty_store b on a.store_id=b.store_id')
			->where($andwhere." and (goods_name like '%{$q}%' or keywords like '%{$q}%')")->cache(true,TPSHOP_CACHE_TIME)->getField("goods_id",true);
			
			
			//判断记录关键词
			if($q && $filter_goods_id){
				$pds=M('user_record')->where("user_id=".$user_id." and `keyword`='".$q."'")->order('id desc')->cache(true,TPSHOP_CACHE_TIME)->getField('click');
				if(empty($pds)){
					$clicks=50;
					$pdscount=M('user_record')->where("user_id=".$user_id)->count();
					if($pdscount>50)
						M('user_record')->where("user_id=".$user_id)->order('id asc')->limit('5')->delete();
				}else{
					$clicks=$pds+1;
					M('user_record')->where("user_id=".$user_id." and `keyword`='".$q."'")->delete();
				}
					 M('user_record')->add([
						 'keyword'=>$q,
						 'user_id'=>$user_id,
						 'click'=>$clicks
					 ]);
			}
		}
	    if(!empty($is_activity)){
		    $time = time();
		    $activitywhere = 'p.start_time <'.$time.' and p.end_time >'.$time.' and a.prom_id!=0';
		    $filter_goods_id = M('goods a')
			->join('ty_store b on a.store_id=b.store_id')
			->join('ty_prom_goods p on p.id=a.prom_id')
			->where($activitywhere." and a.goods_id in (".  implode(',', $filter_goods_id).")")->getField("goods_id",true);
		}
    	// 过滤帅选的结果集里面找商品
//    	if($brand_id || $price)// 品牌或者价格
//    	{
//    		$goods_id_1 = $goodsLogic->getGoodsIdByBrandPrice($brand_id,$price); // 根据 品牌 或者 价格范围 查找所有商品id
//    		$filter_goods_id = array_intersect($filter_goods_id,$goods_id_1); // 获取多个帅选条件的结果 的交集
//    	}

    	$filter_menu  = $goodsLogic->get_filter_menu($filter_param,'search'); // 获取显示的帅选菜单
    	$filter_price = $goodsLogic->get_filter_price($filter_goods_id,$filter_param,'search'); // 帅选的价格期间
		
    	$filter_brand = $goodsLogic->get_filter_brand($filter_goods_id,$filter_param,'search',1); // 获取指定分类下的帅选品牌    	 
    	
    	$count = count($filter_goods_id);
    	$page = new Page($count,16);
    	$page->firstRow = $p * $page->listRows;
    	
    	if($count > 0)
    	{
                $goods_list = M('goods')
				->field('original_img,goods_id,cat_id3,goods_sn,goods_name,shop_price,prom_id,prom_type,comment_count,sales_sum,is_on_sale,is_delete,floating,sorts,store_id,jifen_price')
				->where("goods_id in (".  implode(',', $filter_goods_id).") and is_on_sale=1 and is_delete=0 and goods_state=1")
//                    ->order(array($sort=>$sort_asc))->limit($page->firstRow.','.$page->listRows)->select();
				->order($sortArr)->limit($page->firstRow.','.$page->listRows)->select();
    		$filter_goods_id2 = get_arr_column($goods_list, 'goods_id');
    	}
 
    	$goods_category = M('goods_category')->where('is_show=1')->getField('id,name,parent_id,level'); // 键值分类数组
    	$fast_flag = M('users')->where("user_id=".$user_id)->cache(true,TPSHOP_CACHE_TIME)->getField('fast_flag');
    	foreach ($goods_list as $key=>$value)
    	{
			$quyu_price=quyu_price($this->fenbu_id,$value['store_id']);
			$goods_list[$key]['image'] = C('MYOSS')['url'].$value['original_img'];
			$goods_list[$key]['shop_price'] = geshi($value['shop_price']*($value['floating']/100)*$quyu_price);//浮点计算

			$goods_list[$key]['shop_price'] +=yj_price($value['goods_id'],$goods_list[$key]['shop_price'],$this->fenbu_id);

            $goods_list[$key]['shop_price'] = geshi($goods_list[$key]['shop_price']);
			$goods_list[$key]['status_status']=0;
            //查询是否快线店铺
            $store = M('store')->where(['store_id'=>$value['store_id']])->find();
            if ($store['fast_flag'] && $fast_flag == 1){
                $goods_list[$key]['fast_text'] = '快线';
            }
                // 商品分类页优惠折扣显示 20181129 亮 START
                if (($value['prom_id'] >0) && $value['prom_id']){
                    $prom_goods = M('prom_goods')->where(array('id'=>$value['prom_id']))->find();
					$prom_code = C('MYOSS')['url'].$prom_goods['prom_code'];
                    
                    $datass = time();
                    if (($datass > $prom_goods['start_time']) && ($datass < $prom_goods['end_time'])){
						$statusss = 1;
                        if ($prom_goods['type'] == 0){
                            $prom_goods_price = geshi($goods_list[$key]['shop_price'] * ($prom_goods['expression'] / 100)); //活动折扣
                            $prom_goods_content = 0;
                        }elseif($prom_goods['type'] == 1){
                            $prom_goods_price = $goods_list[$key]['shop_price'] - $prom_goods['expression'];
                            $prom_goods_content = 0; 
                        }elseif($prom_goods['type'] == 2){
                            $prom_goods_price = $prom_goods['expression'];
                            $prom_goods_content = 0;
                        }elseif($prom_goods['type'] == 5){
                             $prom_goods_price = geshi($goods_list[$key]['shop_price'] * ($prom_goods['expression'] / 100)); //活动折扣
                            $prom_goods_content = 0;
                        }else{
                            $prom_goods_price = $goods_list[$key]['shop_price'];
                            $prom_goods_content = "购买赠送代金券$prom_goods[expression]元";
                        }
						$goods_list[$key]['expression'] =$prom_goods['expression'];
						$goods_list[$key]['expressions'] =huodong_name($prom_goods['type'],$prom_goods['expression']);//'活动！'.str_replace("0","",$prom_goods['expression']).'折';
						$goods_list[$key]['prom_goods_price'] = $prom_goods_price;
						$goods_list[$key]['prom_goods_content'] = $prom_goods_content;
						$goods_list[$key]['prom_code'] = $prom_code;
						$goods_list[$key]['status_status'] = $statusss;
                    }
                }

				if($user_id=='61')
				$goods_list[$key]['shop_price']='登陆查看'; //浮点计算
    	}
    	

    	$list['goods_list'] = $goods_list;
        $i = 1;
    	//菜单
        foreach($filter_menu as $k => $v) // 依照app端的要求 去掉 键名
        {
            $v['name'] = $v['text'];
            unset($v['text']);
            $list['filter_menu'][] = $v;  // 帅选规格
        }
       
        // 品牌
        foreach($filter_brand as $k => $v) // 依照app端的要求 去掉 键名
        {
            $list['filter_brand'][] = array('name'=>$v['name'],'href'=>$v['href'],'brand_id'=>$v['brand_id'],'id'=>$i++);
        }

        // 价格
        foreach($filter_price as $k => $v) // 依照app端的要求 去掉 键名
        {
            $list['filter_price'][] = array('name'=>$v['value'],'href'=>$v['href'],'id'=>$i++);
        }
        
        $list['sort'] =  $sort;
        $list['sort_asc'] =  $sort_asc;
    	$sort_asc = $sort_asc == 'asc' ? 'desc' : 'asc';
        $list['orderby_default'] = urldecode(U("Goods/search",$filter_param,'')); // 默认排序
        $list['orderby_sales_sum'] = urldecode(U("Goods/search",array_merge($filter_param,array('sort'=>'sales_sum','sort_asc'=>'desc')),'')); // 销量排序
        $list['orderby_price'] = urldecode(U("Goods/search",array_merge($filter_param,array('sort'=>'shop_price','sort_asc'=>$sort_asc)),'')); // 价格
        $list['orderby_comment_count'] = urldecode(U("Goods/search",array_merge($filter_param,array('sort'=>'comment_count','sort_asc'=>'desc')),'')); // 评论
        $list['orderby_is_new'] = urldecode(U("Goods/search",array_merge($filter_param,array('sort'=>'is_new','sort_asc'=>'desc')),'')); // 新品
    	C('TOKEN_ON',false); //echo $list['goods_list'][0]['shop_price'];
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$list );

        $json_str = json_encode($json_arr,true);
        exit($json_str);
    }
    

    
    /**
     * 获取商品列表
     */
    public function goodsInfo(){
        $goods_id = intval($_REQUEST['id']);
		$user_id=$this->user_id;
        $where['goods_id'] = $goods_id;
        $model = M('Goods');
        $goods  = $model->where($where)->find();
       
        //检查有没有规格，没有就创建 by sofwu
        $specGoodsPrice = M('spec_goods_price')->where(['goods_id'=>$goods_id])->find();
        if(!$specGoodsPrice && $goods['shop_price'] != 0){
            $goodsTypeId = M('goods_type')->where(['name'=>'默认类型','store_id'=>$goods['store_id']])->getField('id');
            if (!$goodsTypeId){
                $goodsTypeId = M('goods_type')->add(['name'=>'默认类型','store_id'=>$goods['store_id']]);
            }

            M('goods')->where(['goods_id'=>$goods_id])->save(['goods_type'=>$goodsTypeId]);

            $spec_id = M('spec')->where(['name' => '默认规格', 'goods_type_id' => $goodsTypeId, 'store_id' => $goods['store_id']])->getField('id');
            if(!$spec_id){
                $spec_id = M('spec')->add(['name' => '默认规格', 'order' => 1, 'store_id' => $goods['store_id'], 'goods_type_id' => $goodsTypeId]);
            }
            $goodsSpecItemId = M('spec_item')->add(['spec_id' => $spec_id, 'item' => '个', 'store_id' => $goods['store_id'], 'goods_id' => $goods['goods_id'], 'sort' => 1]);

//            $goodsSpecId = M('spec')->add(['name'=>'默认规格','order'=>1,'store_id'=>$goods['store_id'],'goods_type_id'=>$goodsTypeId]);
//            $goodsSpecItemId = M('spec_item')->add(['spec_id'=>$goodsSpecId,'item'=>'个','store_id'=>$goods['store_id'],'goods_id'=>$goods_id,'sort'=>1]);
            M('spec_goods_price')->add(['goods_id'=>$goods_id,'key'=>$goodsSpecItemId,'key_name'=>'默认规格:个',
                'price'=>$goods['shop_price'],
                'store_count'=>$goods['store_count'],
                'qipi_num'=>1,
                'sku'=>$goods['sku'],
                'store_id'=>$goods['store_id']
            ]);
        }
		
		$quyu_price=quyu_price($this->fenbu_id,$goods['store_id'],$goods['goods_id']);


        $store = M('store')->where(array('store_id' => $goods['store_id']))->where("INSTR(quyu_stop,'" . $this->fenbu_id . "')=0 or quyu_stop is null or quyu_stop is NULL")->find();
        $blacklist = M('blacklist')->where(['store_id'=>$goods['store_id'],'user_id'=>$this->user_id])->find();
        if ((!$store || ($store && $store['store_state'] == 0)) || $blacklist && $goods['prom_type'] != 101) {
            $json_arr = array('status' => -1, 'msg' => '店铺已关闭', 'result' => '');
            $json_str = json_encode($json_arr);
            exit($json_str);
        }

        // 处理商品属性
        $goods_attribute = M('GoodsAttribute')->getField('attr_id,attr_name'); // 查询属性
        $goods_attr_list = M('GoodsAttr')->where("goods_id = $goods_id")->select(); // 查询商品属性表 
        foreach($goods_attr_list as $key => $val)
        {
            $goods_attr_list[$key]['attr_name'] = $goods_attribute[$val['attr_id']];
        }
        $goods['goods_attr_list'] = $goods_attr_list ? $goods_attr_list : '';
        
        // 处理商品规格
        $Model = new \Think\Model();
        // 商品规格 价钱 库存表 找出 所有 规格项id shadow
        //$keys = M('SpecGoodsPrice')->where("goods_id = $goods_id")->getField("GROUP_CONCAT(`key` SEPARATOR '_') "); 
		$items_id =M('spec_goods_price')->field("key")->where("goods_id =".$goods_id)->select();
        if($items_id)
        {
             $specImage =  M('SpecImage')->where("goods_id = $goods_id and src != '' ")->getField("spec_image_id,src");// 规格对应的 图片表， 例如颜色
             //$keys = str_replace('_',',',$keys);
			 foreach($items_id as $v){
			 	$myitem_id.=$v['key'].'_';
			 }
			 $myitem_id=rtrim($myitem_id, "_");
			 $keys = str_replace('_',',',$myitem_id);
			 //$myitem_id = explode('_', $myitem_id);
			 
			 
             $sql  = "SELECT a.name,a.order,b.* FROM __PREFIX__spec AS a INNER JOIN __PREFIX__spec_item AS b ON a.id = b.spec_id WHERE b.id IN($keys) ORDER BY  a.order,b.sort,a.id";
             $filter_spec2 = $Model->query($sql); 
             $time = time();
             foreach($filter_spec2 as $key => $val)
             {  
                 $huodong = '';
                 $item_id = $val['id'];
                 //判断是否有活动
                 $huodong = M('prom_goods')->where("start_time <$time and end_time>$time and goods_key like '%\"$item_id\"%'")->getField('type');
                 $filter_spec[] = array(
                     'spec_name'=>$val['name'],
                     'item_id'=> $val['id'],
                     'item'=> $val['item'],
					 'src'=>$specImage[$val['id']] ? C('MYOSS')['url'].$specImage[$val['id']] : '',
					 'type'=>$huodong,
                     );
             }
             $goods['goods_spec_list'] = $filter_spec;
        }
	   //$goods['goods_content'] = str_replace('https://shop.lswjsc.com/', C('MYOSS')['url'].'/', $goods['goods_content']);
	   $goods['goods_content'] = str_replace('https://shop.lswjsc.com/',C('MYOSS')['url'].'/', $goods['goods_content']);
	   $goods['goods_content'] = html_entity_decode($goods['goods_content']);
	   //$goods['goods_content'] .='<img style="width:100%" src="'.C('MYOSS')['url'].'/shadow/xuzhis.png"/>';
       //$goods['original_img'] = SITE_URL.$goods['original_img'];       
	   //$goods['original_img'] = C('MYOSS')['url'].str_replace('/Public/', '', $goods['original_img']);
	   $goods['original_img'] = C('MYOSS')['url'].$goods['original_img'];
       $specs = $goods['goods_spec_list'];
       $pos = 0;
       $keys = array();
       foreach ($specs as $key=>$value)
       {
       	   if(!array_key_exists($value['spec_name'], $keys))
       	       $keys[$value['spec_name']] = $pos++;
       }
       
       foreach ($specs as $key=>$value)
       {
       	$value['isClick'] = 0;
       	$spec_arrays[$keys[$value['spec_name']]][] = $value;
       	
       }
       
       foreach ($spec_arrays as $key=>$value)
       {
       	$spec_arrays[$key][0]['isClick'] = 1;
       
       }       
	   
       $goods['goods_spec_list'] = $spec_arrays;
       
	   //判断商品是否被收藏过
	   $count = M('GoodsCollect')->where("user_id = {$user_id} and goods_id = $goods_id")->count();
	   if(!empty($count)){
		   
		   $goods['is_favorite']=1;
		   
	   }else{ 
		   
		   $goods['is_favorite']=0;
	   }
        //获取秒杀信息
        $ymd = date("Y-m-d");
        $hours = date("H");
        $miaosha = M('miaosha_goods')->where("goods_id = $goods_id and open_time = '{$ymd}' and start_time = '{$hours}'")->find();
        if($miaosha){
            $sell_num = M('order_goods')->where(array('prom_type'=>4,'prom_id'=>$miaosha['id']))->getField('sum(goods_num)');
            if(!$sell_num){$sell_num = 0;}
            if($sell_num < $miaosha['ms_num']){
                $return['is_miaosha'] = 1;
                $return['miaosha_goods'] = $miaosha;
                $return['miaosha_goods']['sell_num'] = $sell_num;
                $return['miaosha_goods']['time'] = strtotime($miaosha['open_time'].' '.$miaosha['start_time'].':00:00')+3600-time();
                //处理规格
                //等后台能测试出来再写
            }else{ 
                $return['is_miaosha'] = 0;
            }
        }else{
            $return['is_miaosha'] = 0; 
        }

	   //获取对应店铺资料
		if($goods['store_id']){
			$stores=$this->getStoreinfo($goods['store_id']);
			
			$return['store'] = $stores;
		}
		$user_id = $this->user_id; // 用户id
		
        if($user_id){
            $api = "https://imessage.zczmer.com/api/user/getStoreUid";
            $data = [
                'platform_id' => "3",
                'application_id' => "8",
                'store_id' => $goods['store_id'],
                'user_id'=>$user_id
            ];
            $response = httpRequest($api, 'post' ,$data);
            // dump($response);
            $res = json_decode($response,true);
            if($res['code']==1){
                $return['store']['uid'] = $res['result'];
            }else{
                $return['store']['uid'] = 0;
            }
        }
        
		$discount = 1;
        if ($user_id) {
            $user = M('users')->where("user_id = {$user_id}")->find();
			$discount=$user['discount'];
        }

		if($discount){
			$goods['shop_price']=$discount*$goods['shop_price'];
		}
        $float = check_float($goods['store_id'],$this->user_id,$goods['goods_id']);
        $goods['floating'] = $goods['floating']+$float;
		 $goods['shop_price']=geshi($goods['shop_price']*$goods['floating']/100*$quyu_price); //shadow浮动价
        if($goods['stop_yijia'] == 1){
            $goods['shop_price']+=yj_price($goods['goods_id'],$goods['shop_price'],$this->fenbu_id);
        }
        
            $api = "https://imessage.zczmer.com/api/user/getStoreUid";
            $data = [
                'platform_id' => "3",
                'application_id' => "8",
                'store_id' => $goods['store_id'],
                'user_id'=>$user_id
            ];
            $response = httpRequest($api, 'post' ,$data);
            // dump($response);
            $res = json_decode($response,true);
            if($res['code']==1){
                $return['store']['uid'] = $res['result'];
            }else{
                $return['store']['uid'] = 0;
            }
		 
        $goods['shop_price'] = geshi($goods['shop_price']);
		 if($this->user_id=='61')
		 $goods['shop_price']='登陆查看'; //浮点计算

        //查询是否快线店铺 by sofwu
        if ($store['fast_flag']) {
            $goods['expressions'] = '快线';
        }
        $goods['unit'] = '';
		 $return['goods'] = $goods;
		 
		 $goods_guanlian=M('goods')->field('goods_id,stop_yijia,goods_name,original_img,shop_price,floating')->where(array('goods_id'=>array('in',$goods['guanlian'])))->where('is_on_sale=1 and is_delete=0 and goods_state=1 and (INSTR(quyu_stop,"\"'.$this->fenbu_id.'\"")=0 or quyu_stop is NULL)')->select();
		 foreach($goods_guanlian as $key => $val){
			 $goods_guanlian[$key]['goods_name']=mb_substr($val['goods_name'], 0,8,'utf-8');
			 $goods_guanlian[$key]['original_img']=C('MYOSS')['url'].$val['original_img'];
             $float = check_float($val['store_id'],$this->user_id,$val['goods_id']);
             $goods_guanlian[$key]['floating'] = $val['floating']+$float;
			 $goods_guanlian[$key]['shop_price']=geshi($goods_guanlian[$key]['shop_price']*($goods_guanlian[$key]['floating']/100)*$quyu_price); //浮动价
            if($val['stop_yijia'] == 1){
                $goods_guanlian[$key]['shop_price']+=yj_price($val['goods_id'],$goods_guanlian[$key]['shop_price'],$this->fenbu_id);
            }
			 
			 
			 if($user_id=='61')
			 $goods_guanlian['shop_price']='登陆查看'; //浮点计算
		 }
		 
		 $youlike=M('goods')->field('goods_id,stop_yijia,goods_name,original_img,shop_price,floating,store_id')->where(array('store_id'=>array('in',$goods['store_id'])))->where('is_on_sale=1 and is_delete=0 and goods_state=1 and (INSTR(quyu_stop,"\"'.$this->fenbu_id.'\"")=0 or quyu_stop is NULL)')->order('sales_sum desc')->limit(6)->select();
		 foreach($youlike as $key => $val){
		 			 $youlike[$key]['goods_name']=mb_substr($val['goods_name'], 0,8,'utf-8');
					 $youlike[$key]['original_img']=C('MYOSS')['url'].$val['original_img'];
                     $float = check_float($val['store_id'],$this->user_id,$val['goods_id']);
                     $youlike[$key]['floating'] = $val['floating']+$float;
					 $youlike[$key]['shop_price']=geshi($youlike[$key]['shop_price']*($youlike[$key]['floating']/100)*$quyu_price); //浮动价
					 
                    if($val['stop_yijia'] == 1){
                        $youlike[$key]['shop_price']+=yj_price($val['goods_id'],$youlike[$key]['shop_price'],$this->fenbu_id);
                    }
					 
					 

                     $youlike[$key]['shop_price'] = $user_id=='61' ? '登陆查看' : geshi($youlike[$key]['shop_price']);
		 }
		 
		 $return['goods_guanlian']  = $goods_guanlian;
		 $return['youlike']  = $youlike;
		 $spec_goods_price=M('spec_goods_price')->where("goods_id = $goods_id")->getField("key,price,store_count,qipi_num,goods_id,spu"); // 规格 对应 价格 库存表
		 foreach($spec_goods_price as $key=>$vs){ //处理浮动价shadow
             if($vs['price'] == 0){
                 unset($spec_goods_price[$key]);
             }else{
                 if($discount){
        			$vs['price']=$discount*$vs['price'];
        		}

                 $spec_goods_price[$key]['price']=sanwei($vs['price']*($goods['floating']/100)*$quyu_price);
                    if($goods['stop_yijia'] == 1){
                        $spec_goods_price[$key]['price']+=yj_price($vs['goods_id'],$spec_goods_price[$key]['price'],$this->fenbu_id);
                    }
                     
                     $spec_goods_price[$key]['price']=\floatval(sanwei($spec_goods_price[$key]['price']));


             }


			 if($user_id=='61')
			 $spec_goods_price[$key]['price']='登陆查看'; //浮点计算
		 }
        $return['spec_goods_price']  =$spec_goods_price;
        
        if($user_id=='61')
			 $return['spec_goods_price']='登陆查看'; //浮点计算
        
        $return['gallery'] = M('goods_images')->field('image_url')->order('`sort_id` asc')->where(array('goods_id'=>$goods_id))->select();
		
        foreach($return['gallery'] as $key => $val){
		   $return['gallery'][$key]['image_url'] = C('MYOSS')['url'].$return['gallery'][$key]['image_url'];
        }
		array_unshift($return['gallery'],array('image_url'=>$goods['original_img']));// 插入主图到相册
        //获取最近的两条评论
        //$latest_comment = M('comment')->where("goods_id={$goods_id} AND is_show=1 AND parent_id=0")->order("add_time desc")->select();//->limit(2)
        $latest_comment = $model->field('c.*,u.nick_name as nick_name,u.head_pic as headPic')->table(C('DB_PREFIX').'comment c')->join('LEFT JOIN __USERS__ u ON u.user_id = c.user_id')->where("goods_id={$goods_id} AND is_show=1")->order('add_time DESC')->select();
        foreach ($latest_comment as $key=>$value)
        {
            $latest_comment[$key]['add_time'] = date("Y.m.d ", $value['add_time']) ;
           
            $latest_comment[$key]['img']  = json_decode($latest_comment[$key]['img']);
            if(!empty($latest_comment[$key]['img'][0])){
	    	foreach ( $latest_comment[$key]['img'] as $k =>$v){
				$latest_comment[$key]['img'][$k] =  C('MYOSS')['url'].$v;
	        }
	    }else{
	    	$latest_comment[$key]['img'] = '';
	    }
	    if($latest_comment[$key]['head_pic'] == NULL){
	    	$latest_comment[$key]['head_pic'] = $value['headPic'];
	    }else{
			$latest_comment[$key]['head_pic'] = C('MYOSS')['url'].$value['head_pic'];
	    }
	    if($latest_comment[$key]['username'] == NULL){
	    	$latest_comment[$key]['username'] = $value['nick_name'];
	    }else{
	    	$latest_comment[$key]['username'] = $value['username'];
	    }
        }
        //echo '<pre>';var_dump($latest_comment);exit;
        $return['comment'] = $latest_comment ? $latest_comment : '';
        $time = strtotime($return['goods']['pt_stop_time']);
        if($time > 0){
            $stop_time['stu'] = '1';
            $stop_time['time'] = array(
                date('Y',$time),
                date('m',$time),
                date('d',$time),
                date('H',$time),
                date('i',$time),
                date('s',$time),
                );
        }else{
            $stop_time['stu'] = '0';
        }
        // 商品折扣优惠 商品详情页面的展示 20181121 亮 START
        $goods_prom = M('Goods')->where(array('goods_id'=>$goods_id))->Field('prom_type,prom_id,shop_price,floating,goods_id')->find();
        if($goods_prom['prom_type'] == 4){
            $full_goods = M('prom_goods')->where(array('id'=>$goods_prom['prom_id'],'type'=>4,'start_time'=>['lt',time()],'end_time'=>['gt',time()]))->find();
//            dump($time);
            if(!empty($full_goods)){
                $msg = explode('/',$full_goods['expression']);
                $return['goods']['msg'] = '卖M送N：'.$msg[0].'送'.$msg[1];
            }

        }
        $promgoods = array(); 
		$promgoods['statusss'] = 0;
        if ($goods_prom['prom_id']){
//            $prom_goods = M('prom_goods')->where(array('id'=>$goods_prom['prom_id']))->find();
            $prom_goods = M('prom_goods')->where(array('id'=>$goods_prom['prom_id'],'type'=>['in','0,1,2,3,5']))->find();
            $prom_key = json_decode($prom_goods['goods_key'],true);
            
            if($prom_goods['zd']!=1 && $prom_key){
                $spec_goods_price_list  = M('spec_goods_price')->where(['key'=>['in',implode(',',$prom_key)],'goods_id'=>$goods_id])->select();
                usort($spec_goods_price_list, function($a, $b) {
                    // 先按照 'sort' 键正序排序
                    return $a['price'] - $b['price']; // 正序排序
                });
            }
            if(!empty($spec_goods_price_list[0]['price'])){
                $goods_prom['shop_price'] = $spec_goods_price_list[0]['price'];
            }
            
			$promgoods['prom_goods'] = C('MYOSS')['url'].$prom_goods['prom_code'];
            $data = time();
            if (($data > $prom_goods['start_time']) && ($data < $prom_goods['end_time'])){
				$promgoods['statusss'] = 1;
				if($discount){
        			$goods_prom['shop_price']=$discount*$goods_prom['shop_price'];
        		}
                if ($prom_goods['type'] == 0){
                    $promgoods['prom_goods_price'] = $goods_prom['shop_price'] * ($prom_goods['expression'] / 100);
//                    $promgoods['prom_goods_price'] = $goods_prom['shop_price'] ;
                    $promgoods['prom_goods_content'] = 0;
					$promgoods['zhekou'] = $prom_goods['expression'] / 100;
                }elseif($prom_goods['type'] == 1){
                    $promgoods['prom_goods_price'] = $goods_prom['shop_price'] - $prom_goods['expression'];
//                    $promgoods['prom_goods_price'] = $goods_prom['shop_price'] ;
                    $promgoods['prom_goods_content'] = 0;
					$promgoods['zhekou'] = $prom_goods['expression']; //new
                }elseif($prom_goods['type'] == 2){
                    $promgoods['prom_goods_price'] = $prom_goods['expression'];
                    $promgoods['prom_goods_content'] = 0;
					$promgoods['zhekou'] = $prom_goods['expression']; //new
                }elseif($prom_goods['type'] == 5){
                    $promgoods['prom_goods_price'] = $goods_prom['shop_price'] * ($prom_goods['expression'] / 100);
//                    $promgoods['prom_goods_price'] = $goods_prom['shop_price'];
                    $promgoods['prom_goods_content'] = 0;
                    $promgoods['zhekou'] = $prom_goods['expression'] / 100;
                }else{
                    $promgoods['prom_goods_price'] = $goods_prom['shop_price'];
                    $promgoods['prom_goods_content'] = "购买赠送代金券$prom_goods[expression]元";
                }
				// $promgoods['prom_goods_pricess'] = $promgoods['prom_goods_price'];
				if($prom_goods['type'] != 2){
				    $promgoods['prom_goods_price'] = geshi($promgoods['prom_goods_price']*($goods_prom['floating']/100)*$quyu_price);
				    $promgoods['prom_goods_prices'] = geshi($spec_goods_price_list[0]['price']*($goods_prom['floating']/100)*$quyu_price);
				}else{
				    $promgoods['prom_goods_price'] = geshi($promgoods['prom_goods_price']*$quyu_price);
				    $promgoods['prom_goods_prices'] = geshi($spec_goods_price_list[0]['price']*$quyu_price);
				}
				
                $promgoods['prom_goods_price']+=yj_price($goods_prom['goods_id'],$promgoods['prom_goods_price'],$this->fenbu_id);
                $promgoods['prom_goods_prices']+=yj_price($goods_prom['goods_id'],$promgoods['prom_goods_prices'],$this->fenbu_id);
                $promgoods['prom_goods_price'] = floatval(geshi($promgoods['prom_goods_price']));
                if($this->user_id == 61){
                    $promgoods['prom_goods_price'] = '登陆查看';
                }
                
				$promgoods['jieshu'] = date("Y/m/d H:i:s",$prom_goods['end_time']);
				$promgoods['goods_key'] = $prom_goods['goods_key'];
				$promgoods['type'] = $prom_goods['type'];
				$promgoods['xiangou'] = $prom_goods['xiangou']?'（活动限购：'.$prom_goods['xiangou'].' 件）':'';
				$promgoods['xiangou_num'] = $prom_goods['xiangou'];
            }
		}
        $return['promgoods'] = $promgoods;
        // 商品折扣优惠 商品详情页面的展示 20181121 亮 END
		$basic=tpCache("basic");
		$is_show_store=$basic['app_test'];
		$return['is_show_store'] = $is_show_store;
        $return['stop_time'] = $stop_time;
        
    	//获取满减信息我这个时间段购买了多少钱
        $full = $this->fullList($this->user_id);
	    $return['full'] = $full;
	     //店铺
        $store_full = $this->store_full($goods['store_id'],$goods['store_cat_id1']);
	    $return['store_full'] = $store_full;
	    
	    $return['pay_msg'] = $basic['pay_msg'];
        if(!$goods){
            $json_arr = array('status'=>-1,'msg'=>'没有该商品','result'=>'');
        }else{
            $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$return);
        }
		M('Goods')->where("goods_id=$goods_id")->save(array('click_count'=>$goods['click_count']+1 )); //统计点击数
        $json_str = json_encode($json_arr);
        exit($json_str);
    }
  public function store_full($store_id,$goods_brand_id){
        $full = [];
        $store_id = $store_id;
        $user_id = $this->user_id;
        $store = M('store')->where(['store_id'=>$store_id])->find();
        $time = time();
        $goodsFull = M('goods_full')->where("store_id = $store_id and start_time <=$time and end_time >=$time")->order('id desc')->find();
        // var_dump($goodsFull);
        if(!empty($goodsFull)){
            if($goodsFull['start_time'] < time() && $goodsFull['end_time'] > time() ){
            // var_dump($goodsFull);
            $where = [];
            if(!empty($goodsFull['brand_id'])){
                $brand_id = implode(',',json_decode($goodsFull['brand_id'],true));
                $where['gs.store_cat_id1'] = ['in',$brand_id];
            }
            if(!empty($goodsFull['goods_id'])){
                $goods_id = implode(',',json_decode($goodsFull['goods_id'],true));
                $where['gs.goods_id'] = ['in',$goods_id];
            }
            
            if($goodsFull['type'] == 1){
                $begin = strtotime(date('Y-m-d 00:00:00'));
                $end = strtotime(date('Y-m-d 23:59:59'));
            }else{
                $begin = $goodsFull['start_time'];
                $end = $goodsFull['end_time'];
            }
            
      
            $where['o.user_id'] = $user_id;
            $where['o.order_status'] = ['in','0,1,2'];
            $where['o.store_id'] = $store_id;
            $where['g.full_status'] = 0;
            $where['o.add_time'] = ['between', [$begin, $end]];
            // dump($where);
            //不参与活动的
            // $pgoods = M('order_goods')->where(['full_status'=>0,'order_id'=>['in',$orderids],'store_id'=>$store_id])->sum('(member_goods_price+yijia)*goods_num');
            $myPrice = M('order_goods g')
    	    ->join('ty_order o on o.order_id = g.order_id','left')
    	    ->join('ty_goods gs on gs.goods_id = g.goods_id','left')
    	    ->where($where)
    	    ->sum('(g.member_goods_price+g.yijia)*goods_num');
    	    
            // $myPrice = $price;
            if(empty($myPrice) || $myPrice < 0){
                $myPrice = 0;
            }
            // dump($myPrice);
        		$full = json_decode($goodsFull['full_gift'],true);
        		foreach ($full as $k=>$v){
        		        $price = geshi($v['price'] - $myPrice);
        		        if($price <= 0){
        		            $full[$k]['status'] = 1;
        		            $full[$k]['c_price'] = 0;
        		        }else{
        		            $full[$k]['status'] = 2;
        		            $full[$k]['c_price'] = $price;
        		        }
        		        $full[$k]['myPrice'] = $myPrice;
        		        $full[$k]['name'] = $goodsFull['name'];
        		} 
    		}
    		  //dump($brand_id);
    		if(!empty($goodsFull['brand_id'])){
    		    if(!in_array($goods_brand_id,json_decode($goodsFull['brand_id'],true))){
    		        $full = [];
    		    }
    		}
    		
    		
        }
        return $full;
        
    }
    /*
    总部满减获取
    */
    public function fullList($user_id){

        $data = tpCache('full_reduction');
        $full = [];
        $time = time();
        $goodsFull = M('goods_full')->where("store_id is NULL and start_time <=$time and end_time >=$time")->order('id desc')->find();
        // if(strtotime($data['full_shijian1']) < time() && strtotime($data['full_shijian2']) > time() ){
        if($goodsFull['start_time'] < time() && $goodsFull['end_time'] > time() ){
            $where = [];
            // $myPrices = M('users_price a')
            //     ->cache(true,60)
            //     ->where('a.price != 0 and a.user_id = '.$user_id.' and a.add_time > '.$goodsFull['start_time'].' and a.add_time <'.$goodsFull['end_time'])->select();
            //     // var_dump($myPrices);
            // $myPrice = 0;
            // $price = 0;
            // $orderids = '';
            // foreach ($myPrices as $k=>$v){
            //     $orderids .=$v['order_id'].',';
            //     $price += $v['price'];
            // }
            // if(!empty($orderids)){
            //     $orderids = substr($orderids,0,-1);
            //     $where['o.order_id'] = ['in',$orderids];
            // }
            // dump($orderids);
            //不参与活动的
            // $pgoods = M('order_goods g')
            // ->join
            // ->where(['full_status'=>0,'order_id'=>['in',$orderids]])
            // ->sum('(member_goods_price+yijia)*goods_num');
            
            $begin = $goodsFull['start_time'];
            $end = $goodsFull['end_time'];
            $where['g.full_status'] = 1;
            $where['o.user_id'] = $user_id;
            $where['o.add_time'] = ['between',"$begin,$end"];
            
            if(!empty($goodsFull['brand_id'])){
                $brand_id = implode(',',json_decode($goodsFull['brand_id'],true));
                $where['gs.cat_id1'] = ['in',$goods_id];
            }
            
            $myPrice = M('order_goods g')
    	    ->join('ty_order o on o.order_id = g.order_id','left')
    	    ->join('ty_goods gs on gs.goods_id = g.goods_id','left')
    	    ->where($where)
    	    ->sum('(member_goods_price+yijia)*goods_num');
          
            // var_dump($myPrice);
            // if(empty($myPrice) || $myPrice < 0){
            //     $myPrice = 0;
            // }
            $full = json_decode($goodsFull['full_gift'],true);
            foreach ($full as $k=>$v){
                $price = geshi($v['price'] - $myPrice);
                if($price <= 0){
                    $full[$k]['status'] = 1;
                    $full[$k]['c_price'] = 0;
                }else{
                    $full[$k]['status'] = 2;
                    $full[$k]['c_price'] = $price;
                }
                $full[$k]['myPrice'] = $myPrice;
            }

        }
        return $full;
    }
	public function getStoreinfo($store_id){
		$reurn=array();
        $store = M('store')->where("store_id=$store_id")->field('phone_status,store_id,store_logo,store_name,sc_id,store_desccredit,store_servicecredit,store_deliverycredit,store_phone,grade_id,la,lo,store_address')->find();
		$reurn['sc_name'] = M('store_class')->where(array('sc_id'=>$store['sc_id']))->getField('sc_name');//分类
		$reurn['goods_num'] = M('goods')->where('is_on_sale and is_delete=0 and store_id='.$store_id)->count();//产品数量
		//$reurn['store_logo'] = SITE_URL.$store['store_logo'];
		//$reurn['store_logo'] = C('MYOSS')['url'].str_replace('/Public/', '', $store['store_logo']);
		$reurn['store_logo'] = C('MYOSS')['url'].$store['store_logo'];
		$reurn['store_name'] = $store['store_name'];
		$reurn['store_phone'] =$store['store_phone'];
		if($store['phone_status'] == 0){
		    $reurn['store_phone'] = '-';
		}
		
		$reurn['la'] = $store['la'];
		$reurn['lo'] = $store['lo'];
		$reurn['store_address'] = $store['store_address'];
		$service_rank=M('')->query(" select AVG(service_rank) as service_rank from __PREFIX__comment where store_id = $store_id ");
		$deliver_rank=M('')->query(" select AVG(deliver_rank) as deliver_rank from __PREFIX__comment where store_id = $store_id ");
		$goods_rank=M('')->query(" select AVG(goods_rank) as goods_rank from __PREFIX__comment where store_id = $store_id ");
		if(empty($service_rank[0]['service_rank'])){
			$service_rank[0]['service_rank']=5.0;
		}
		if(empty($deliver_rank[0]['deliver_rank'])){
			$deliver_rank[0]['deliver_rank']=5.0;
		}
		if(empty($goods_rank[0]['goods_rank'])){
			$goods_rank[0]['goods_rank']=5.0;
		}				
		$reurn['store_servicecredit'] =$service_rank[0]['service_rank'];
		$reurn['store_deliverycredit'] = $deliver_rank[0]['deliver_rank'];
		$reurn['store_desccredit'] = $goods_rank[0]['goods_rank'];
		return 	$reurn;	
	}
    /**
     *  goodsPriceBySpec 获取商品价格
     */
    /*
    public function goodsPriceBySpec()
    {        
        $goods_id = I("goods_id"); // 商品id
        $goods_num = I("goods_num");// 商品数量
        $goods = M('Goods')->where("goods_id = $goods_id")->find();
        $goods_price = $goods['shop_price']; // 商品价格 
        
        // 有选择商品规格
        if(!empty($_REQUEST['spec_list']))
        {
            $spec_item = explode(',', $_REQUEST['spec_list']);
            sort($spec_item);
            $spec_item_key = implode('_', $spec_item);
            $specGoodsPrice = M("SpecGoodsPrice")->where("goods_id = $goods_id and `key` = '$spec_item_key'")->find();
            if($specGoodsPrice)
                $goods_price = $specGoodsPrice['price'];
        }    
        $price = $goods_price * $goods_num; // 商品单价乘以数量        
        
        if(!$price){
            $json_arr = array('status'=>-1,'msg'=>'没有查询到价格','result'=>'');
        }else{
            $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$price);
        }
        $json_str = json_encode($json_arr);
        exit($json_str);         
    }
    */
    
    /**
     *  获取商品的缩略图
     */
    function goodsThumImages()
    {        
        $goods_id = I('goods_id');
        $width = I('width');
        $height = I('height');         
        $img_url = SITE_URL.goods_thum_images($goods_id,$width,$height);                
        $image = file_get_contents($img_url);  //假设当前文件夹已有图片001.jpg        
        header('Content-type: image/jpg');
        exit($image);
    }
    
    
    /**
     * 获取某个商品的评价
     */
    function getGoodsComment()
    {        
        $goods_id = I('goods_id');        
        $where = " goods_id = $goods_id  and is_show = 1";
        $count = M('comment')->where($where)->count();
        $_GET['p'] = $_REQUEST['p'];
        $page = new Page($count,10);        
        $list = M('comment')->where($where)->order("comment_id desc")->limit("{$page->firstRow},{$page->listRows}")->select();        
        foreach ($list as $key => $val)
        {
            if(empty($val['img']))
            {
                $list[$key]['img'] = '';
                continue;
            }

            $val['img'] = unserialize($val['img']);

            foreach ($val['img'] as $k => $v)
            {
                //$val['img'][$k] = SITE_URL.$v;
				//$val['img'][$k] = C('MYOSS')['url'].str_replace('/Public/', '', $v);
				$val['img'][$k] = C('MYOSS')['url'].$v;
            }
            $list[$key]['img'] = $val['img']; 
        }
        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$list )));
    }
    /**
     * 收藏商品
     */
    function collectGoods(){
         $this->user_id = I('user_id');
        $goods_id = I('goods_id');
        $type = I('type',0);
//        $count = M('Goods')->where("goods_id = $goods_id and is_on_sale=1 and is_delete=0 and goods_state=1")->count();
        $count = M('Goods')->where(['goods_id'=>$goods_id,'is_on_sale'=>1,'is_delete'=>0,'goods_state'=>1])->find();
        // if(empty($count))  exit(json_encode(array('status'=>1,'msg'=>'收藏商品不存在','result'=>array())));
        //删除收藏商品
        if($type==1){
        	
            M('GoodsCollect')->where("user_id = {$this->user_id} and goods_id = $goods_id")->delete();
            exit(json_encode(array('status'=>1,'msg'=>'成功取消收藏','result'=>array() )));
        }
        $count = M('GoodsCollect')->where("user_id = {$this->user_id} and goods_id = $goods_id")->count();
        if($count > 0)        exit(json_encode(array('status'=>1,'msg'=>'您已收藏过该商品','result'=>array() )));
        M('GoodsCollect')->add(array(
            'goods_id'=>$goods_id,
            'user_id'=>$this->user_id,
            'add_time'=>time(),
        ));
        exit(json_encode(array('status'=>1,'msg'=>'收藏成功','result'=>array() )));
    }

    /**
     * 商品浏览记录
     */
    function liulanGoods(){
        $m = M('GoodsLiulan');
        $this->user_id = I('user_id');
        $goods_id = I('goods_id');
        $type = I('type',0);
        $count = M('Goods')->where("goods_id = $goods_id and is_on_sale=1 and is_delete=0 and goods_state=1")->count();
        if($count == 0)  exit(json_encode(array('status'=>1,'msg'=>'记录商品不存在','result'=>array())));
        //删除收藏商品
        if($type==1){
            
            $m->where("user_id = {$this->user_id} and goods_id = $goods_id")->delete();
            exit(json_encode(array('status'=>1,'msg'=>'成功删除该记录','result'=>array() )));
        }
        $pd=$m->where("user_id = {$this->user_id} and goods_id = $goods_id")->find();
		if($pd){
			$m->where("user_id = {$this->user_id} and goods_id = $goods_id")->setField('add_time',time());
		}else{
			$m->add(array(
            'goods_id'=>$goods_id,
            'user_id'=>$this->user_id,
            'add_time'=>time(),
			));
		}
        
    }


    /**
     * 猜你喜欢/热门推荐
     */
    public function guessYouLike(){
        $p = I('p',1);
        $favourite_goods = M('goods')->where("is_recommend=1 and is_on_sale and is_delete=0")->order('goods_id DESC')->page($p,10)->getField('goods_id,goods_sn,goods_name,shop_price,comment_count,original_img');//首页/购物车/我的 推荐商品
        $goods = array();
        foreach ($favourite_goods as $k => $v){
            $v['original_img']=C('MYOSS')['url'].$v['original_img'];
            $v['shop_price']=$this->user_id  == 61 ? '登陆查看' :$v['shop_price'];
            $goods[] = $v;
        }
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>$goods );
        $json_str = json_encode($json_arr,true);

        exit($json_str);
    }

    //生成商品二维码
    public  function storeQrcode(){ //生产店铺二维码
        $store_id = I('store_id');
        $user_id=I('user_id');
        $store=M("store")->where("store_id=$store_id")->find();//echo json_encode($goods);
        if (!$store){
            $json_arr = array('code'=>1,'msg'=>'店铺不存在');
            $json_str = json_encode($json_arr,true);
            exit($json_str);
        }
        $store_pic_url =$store["store_logo"];
        $store_pic_url=SITE_URL.$store_pic_url;
        $store_pic_save_path = QRCODE_PATH.'/qrcode';

        $store_pic_save_name = md5("v=1.6.2&store_id={$store['store_id']}0&store_name={$store['store_name']}&user_id={$user_id}&store_pic_url={$store_pic_url}"). '.jpg';

        $pic_url=SITE_URL."/Public/goodsqrcode/qrcode".$store_pic_save_name;//echo $pic_url;band

        if (file_exists($store_pic_save_path . $store_pic_save_name)) {

            $json_arr = array('code'=>0,'msg'=>'获取成功','data'=>[
                'goods_name' => $store['goods_name'],
                'pic_url' => $pic_url . '?v=' . time(),
            ] );
            $json_str = json_encode($json_arr,true);
            exit($json_str);
        }

        $store_pic_path = $this->saveTempImage($store_pic_url);
        if (!$store_pic_path){
            $json_arr = array('code'=>1,'msg'=>'获取商品海报失败：商品图片丢失');
            $json_str = json_encode($json_arr,true);
            exit($json_str);
        }
        $store_qrcode_dst = 'Public/qrcode/goods-qrcode-dsts.jpg';
        $font_path = 'Public/fonts/st-heiti-light.ttc';

        $editor = Grafika::createEditor(GrafikaHelper::getSupportEditorLib());
        $editor->open($store_qrcode, $store_qrcode_dst);
        $editor->open($store_pic, $store_pic_path);

        //获取小程序码图片
        $wxapp_qrcode_file_res = $this->getQrcode($store['store_id'], $user_id,'yes');

        if ($wxapp_qrcode_file_res['code'] == 1) {
            unlink($store_pic_path);
            return [
                'code' => 1,
                'msg' => '获取商品海报失败：获取小程序码失败，' . $wxapp_qrcode_file_res['msg'],
            ];
        }

        $wxapp_qrcode_file_path = $wxapp_qrcode_file_res['file_path'];
        $editor->open($wxapp_qrcode, $wxapp_qrcode_file_path);

        $name_size = 30;
        $name_width = 670;
        //店铺描述处理换行
        $store['store_zy']==""?$store['store_zy']='该店铺还没有描述~':$store['store_zy'];
        $name = $this->autowrap($name_size, 0, $font_path, $store['store_zy'], $name_width, 3);

        //裁剪店铺图片
        $editor->resizeFill($store_pic, 130, 130);
        //附加店铺图片
        $editor->blend($store_qrcode, $store_pic, 'normal', 1.0, 'top-left', 30, 30);

        //商城描述
        $editor->text($store_qrcode, $name, 20, 190, 30, new Color('#888888'), $font_path, 0);
        //加店铺名称
        $editor->text($store_qrcode, $store['store_name'].' 店铺', $name_size, 40, 360, new Color('#333333'), $font_path, 0);

        //调整小程序码图片
        $editor->resizeExactWidth($wxapp_qrcode, 240);
        //附加小程序码图片
        $editor->blend($store_qrcode, $wxapp_qrcode, 'normal', 1.0, 'top-left', 470, 230);

        //保存图片
        $editor->save($store_qrcode, $store_pic_save_path . $store_pic_save_name, 'jpeg', 85);

        //删除临时图片
        unlink($store_pic_path);
        unlink($wxapp_qrcode_file_path);
        $json_arr = array('code'=>0,'msg'=>'获取成功','data'=>[
            'store_name' => $store['store_name'],
            'pic_url' => $pic_url . '?v=' . time(),
        ] );
        $json_str = json_encode($json_arr,true);
        exit($json_str);
    }

    /*
     * 生成推荐图片
     * */
    public function driverRecommendation(){
        $user_id = I('user_id');
        if(empty($user_id)){
            $json_arr = array('code'=>0,'msg'=>'缺失user_id');
            $json_str = json_encode($json_arr,true);
            exit($json_str);
        }
        $userInfo = M('users')->where(['user_id'=>$user_id])->find();
        $goods_pic_url = $userInfo["recommendImg"];
        $goods_pic_url=SITE_URL.$goods_pic_url;

        $goods_pic_save_path =QRCODE_PATH.'/users';
        $goods_pic_save_name = md5($user_id). '.jpg';
        $pic_url=SITE_URL."/Public/goodsqrcode/users".$goods_pic_save_name;
        if (file_exists($goods_pic_save_path . $goods_pic_save_name)) {


            $result = array('status'=>1,'msg'=>'获取成功','result'=>[
                'user_id' => $user_id,
                'status' =>1,
                'pic_url' => $pic_url . '?v=' . time(),
            ]);
            $json_str = json_encode($result,true);
            exit($json_str);
        }
        $goods_pic_path = $this->saveTempImage($goods_pic_url);
        if (!$goods_pic_path){
            $json_arr = array('status'=>0,'msg'=>'获取商品海报失败：商品图片丢失');
            $json_str = json_encode($json_arr,true);
            exit($json_str);
        }

        //获取小程序码图片
        $wxapp_qrcode_file_res = $this->getQrcode('',$user_id ,'user');
        $wxapp_qrcode_file_path = $wxapp_qrcode_file_res['file_path'];
        if($userInfo['recommendImg'] != $pic_url){
            M('users')->where(['user_id'=>$user_id])->save(['recommendImg'=>$pic_url]);
        }
        //保存图片
        $editor = Grafika::createEditor(GrafikaHelper::getSupportEditorLib());

        $editor->open($wxapp_qrcode, $wxapp_qrcode_file_path);
        $editor->save($wxapp_qrcode, $goods_pic_save_path . $goods_pic_save_name, 'jpeg', 85);
        unlink($goods_pic_path);
        unlink($wxapp_qrcode_file_path);
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>[
            'user_id' => $user_id,
            'pic_url' => $pic_url . '?v=' . time(),
        ] );
        $json_str = json_encode($json_arr,true);
        exit($json_str);

    }
    
    /*
     * 生成推荐图片
     * */
    public function registerRecommendation(){
        $user_id = I('user_id');
        if(empty($user_id)){
            $json_arr = array('code'=>0,'msg'=>'缺失user_id');
            $json_str = json_encode($json_arr,true);
            exit($json_str);
        }
        $userInfo = M('users')->where(['user_id'=>$user_id])->find();
        $goods_pic_url = $userInfo["recommendImg"];
        $goods_pic_url=SITE_URL.$goods_pic_url;
        
        $goods_pic_save_path ='./Public/registerqrcode/users';
        $goods_pic_save_name = md5($user_id). '.jpg';
        $pic_url=SITE_URL."/Public/registerqrcode/users".$goods_pic_save_name;
        if (file_exists($goods_pic_save_path . $goods_pic_save_name)) {
            
            
            $result = array('status'=>1,'msg'=>'获取成功','result'=>[
                'user_id' => $user_id,
                'status' =>1,
                'pic_url' => $pic_url . '?v=' . time(),
            ]);
            $json_str = json_encode($result,true);
            exit($json_str);
        }
        $goods_pic_path = $this->saveTempImage($goods_pic_url);
        if (!$goods_pic_path){
            $json_arr = array('status'=>0,'msg'=>'获取商品海报失败：商品图片丢失');
            $json_str = json_encode($json_arr,true);
            exit($json_str);
        }
        
        //获取小程序码图片
        $wxapp_qrcode_file_res = $this->getQrcode('', $user_id,'reguser');
        $wxapp_qrcode_file_path = $wxapp_qrcode_file_res['file_path'];
        if($userInfo['recommendImg'] != $pic_url){
            M('users')->where(['user_id'=>$user_id])->save(['recommendImg'=>$pic_url]);
        }
        //保存图片
        $editor = Grafika::createEditor(GrafikaHelper::getSupportEditorLib());
        
        $editor->open($wxapp_qrcode, $wxapp_qrcode_file_path);
        $editor->save($wxapp_qrcode, $goods_pic_save_path . $goods_pic_save_name, 'jpeg', 85);
        unlink($goods_pic_path);
        unlink($wxapp_qrcode_file_path);
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>[
            'user_id' => $user_id,
            'pic_url' => $pic_url . '?v=' . time(),
        ] );
        $json_str = json_encode($json_arr,true);
        exit($json_str);
        
    }
    
		 /*
     * 生成推荐图片
     * */
    public function StoreRecommendation(){
        $store_id = I('store_id');
        $goods = new GoodsController();
        if(empty($store_id)){
            $json_arr = array('code'=>0,'msg'=>'缺失store_id');
            $json_str = json_encode($json_arr,true);
            exit($json_str);
        }
        $store = M('store')->where(['store_id'=>$store_id])->find();
        $user_id = $store['user_id'];
        $goods_pic_url = $store["recommendImg"];
        $goods_pic_url=SITE_URL.$goods_pic_url;

        $goods_pic_save_path =QRCODE_PATH.'/store/';
        $goods_pic_save_name = md5($store_id). '.jpg';
        $pic_url=SITE_URL."/Public/goodsqrcode/store/".$goods_pic_save_name;
       
        if (file_exists($goods_pic_save_path . $goods_pic_save_name)) {

            $result = array('status'=>1,'msg'=>'获取成功','result'=>[
                'store_id' => $store_id,
                'status' =>1,
                'pic_url' => $pic_url . '?v=' . time(),
            ]);
            $json_str = json_encode($result,true);
            exit($json_str);
        }
        $goods_pic_path = $goods->saveTempImage($goods_pic_url);
        if (!$goods_pic_path){
            $json_arr = array('status'=>0,'msg'=>'获取海报失败：商品图片丢失');
            $json_str = json_encode($json_arr,true);
            exit($json_str);
        }

        //获取小程序码图片
        $wxapp_qrcode_file_res = $goods->getQrcode($store_id, '','store_id');
        
        $wxapp_qrcode_file_path = $wxapp_qrcode_file_res['file_path'];
        if($store['recommendimg'] != $pic_url){
            M('store')->where(['store_id'=>$store_id])->save(['recommendimg'=>$pic_url]);
        }
      
        //保存图片
        $editor = Grafika::createEditor(GrafikaHelper::getSupportEditorLib());
        $editor->open($wxapp_qrcode, $wxapp_qrcode_file_path);
        $editor->save($wxapp_qrcode, $goods_pic_save_path . $goods_pic_save_name, 'jpeg', 85);
        unlink($goods_pic_path);
        unlink($wxapp_qrcode_file_path);
        $json_arr = array('status'=>1,'msg'=>'获取成功','result'=>[
            'user_id' => $user_id,
            'pic_url' => $pic_url . '?v=' . time(),
        ] );
        $json_str = json_encode($json_arr,true);
        exit($json_str);

    }
	public  function goodsQrcode(){
		$goods_id = I('goods_id');
		$user_id=I('user_id');
		$goods=M("goods")->where("goods_id=$goods_id")->find();//echo json_encode($goods);
        if (!$goods){
			$json_arr = array('code'=>1,'msg'=>'商品不存在');
			$json_str = json_encode($json_arr,true);
			exit($json_str);
		}
        //$store = Store::findOne($this->store_id);

        $goods_pic_url = $goods["original_img"];
		$goods_pic_url=C('MYOSS')['url'].$goods_pic_url;
        $goods_pic_save_path =QRCODE_PATH.'/qrcode';
        //获取秒杀信息
		$goods_id=$goods['goods_id'];
        $ymd = date("Y-m-d");
        $hours = date("H");
        $goods['shop_price'] = '扫码查看优惠';
        $miaosha = M('miaosha_goods')->where("goods_id = $goods_id and open_time = '{$ymd}' and start_time = '{$hours}'")->find();
        if($miaosha){
            $sell_num = M('order_goods')->where(array('prom_type'=>4,'prom_id'=>$miaosha['id']))->getField('sum(goods_num)');
            if(!$sell_num){$sell_num = 0;}
            if($sell_num < $miaosha['ms_num']){

                $goods['shop_price'] = $miaosha['ms_price'];
            }
			$time=time();
			$goods_pic_save_name = md5("v=1.6.2&goods_id={$goods['goods_id']}&goods_name={$goods['goods_name']}&store_name={$goods['store_id']}&user_id={$user_id}&goods_pic_url={$goods_pic_url}&ms_price={$miaosha['ms_price']}") . '.jpg';
        }else{
			$goods_pic_save_name = md5("v=1.6.2&goods_id={$goods['goods_id']}&goods_name={$goods['goods_name']}&store_name={$goods['store_id']}&user_id={$user_id}&goods_pic_url={$goods_pic_url}") . '.jpg';			
			
		}
		
		$pic_url=SITE_URL."/Public/goodsqrcode/qrcode".$goods_pic_save_name;
        if (file_exists($goods_pic_save_path . $goods_pic_save_name)) {
			
			$json_arr = array('code'=>0,'msg'=>'获取成功','data'=>[
                    'goods_name' => $goods['goods_name'],
                    'pic_url' => $pic_url . '?v=' . time(),
                ] );
			$json_str = json_encode($json_arr,true);			
			exit($json_str);					
        }
        $goods_pic_path = $this->saveTempImage($goods_pic_url);
        if (!$goods_pic_path){
			$json_arr = array('code'=>1,'msg'=>'获取商品海报失败：商品图片丢失');
			$json_str = json_encode($json_arr,true);
			exit($json_str);
		}
        $goods_qrcode_dst = 'Public/qrcode/goods-qrcode-dst.jpg';
        $font_path = 'Public/fonts/st-heiti-light.ttc';
		
        $editor = Grafika::createEditor(GrafikaHelper::getSupportEditorLib());
        $editor->open($goods_qrcode, $goods_qrcode_dst);
        $editor->open($goods_pic, $goods_pic_path);
		
        //获取小程序码图片
		
        $wxapp_qrcode_file_res = $this->getQrcode($goods['goods_id'], $user_id);

        if ($wxapp_qrcode_file_res['code'] == 1) {
            unlink($goods_pic_path);
            return [
                'code' => 1,
                'msg' => '获取商品海报失败：获取小程序码失败，' . $wxapp_qrcode_file_res['msg'],
            ];
        }
        $wxapp_qrcode_file_path = $wxapp_qrcode_file_res['file_path'];
        $editor->open($wxapp_qrcode, $wxapp_qrcode_file_path);

        $name_size = 30;
        $name_width = 670;
        //商品名称处理换行
        $name = $this->autowrap($name_size, 0, $font_path, $goods['goods_name'], $name_width, 2);
        //加商品名称
        $editor->text($goods_qrcode, $name, $name_size, 40, 750, new Color('#333333'), $font_path, 0);

        //裁剪商品图片
        //$editor->crop($goods_pic, 670, 670, 'smart');
        $editor->resizeFill($goods_pic, 670, 670);
        //附加商品图片
        $editor->blend($goods_qrcode, $goods_pic, 'normal', 1.0, 'top-left', 40, 40);

        //加商品价格
        $editor->text($goods_qrcode, '￥' . $goods['shop_price'], 45, 30, 910, new Color('#ff4544'), $font_path, 0);

        //加商城名称
        $editor->text($goods_qrcode, $store->name, 20, 40, 1170, new Color('#888888'), $font_path, 0);

        //调整小程序码图片
        $editor->resizeExactWidth($wxapp_qrcode, 240);
        //附加小程序码图片
        $editor->blend($goods_qrcode, $wxapp_qrcode, 'normal', 1.0, 'top-left', 470, 1040);
		
        //保存图片
        $editor->save($goods_qrcode, $goods_pic_save_path . $goods_pic_save_name, 'jpeg', 85);

        //删除临时图片
        unlink($goods_pic_path);
        unlink($wxapp_qrcode_file_path);	
		$json_arr = array('code'=>0,'msg'=>'获取成功','data'=>[
                    'goods_name' => $goods['goods_name'],
                    'pic_url' => $pic_url . '?v=' . time(),
                ] );
		$json_str = json_encode($json_arr,true);			
		exit($json_str);		
	}
    //生成拼团邀请二维码
    public  function pintQrcode(){
        
        $pint_id = I('pint_id');
        $user_id = I('user_id');
        $pint=M("pint")->where("pint_id=$pint_id")->find();
        if (!$pint){
            $json_arr = array('code'=>1,'msg'=>'拼团不存在');
            $json_str = json_encode($json_arr,true);
            exit($json_str);
        }
        //$store = Store::findOne($this->store_id);
        $goods_id = $pint['goods_id'];
        $goods=M("goods")->where("goods_id=$goods_id")->find();
        if (!$goods){
            $json_arr = array('code'=>1,'msg'=>'商品不存在');
            $json_str = json_encode($json_arr,true);
            exit($json_str);
        }
		$goods_pic_url = M("goods")->where("goods_id=$goods_id")->getField("original_img");
        //$goods_pic_url=SITE_URL.$goods_pic_url;
		//$goods_pic_url=C('MYOSS')['url'].str_replace('/Public/', '',$goods_pic_url);
		$goods_pic_url=C('MYOSS')['url'].$goods_pic_url;
        $goods_pic_save_path = QRCODE_PATH.'/qrcode';
        $goods_pic_save_name = md5("v=1.6.2&pint_id={$pint['pint_id']}&goods_id={$goods['goods_id']}&goods_name={$goods['goods_name']}&store_name={$goods['store_id']}&user_id={$user_id}&goods_pic_url={$goods_pic_url}") . '.jpg';
        $pic_url=SITE_URL."/Public/goodsqrcode/qrcode".$goods_pic_save_name;
        if (file_exists($goods_pic_save_path . $goods_pic_save_name)) {
            
            $json_arr = array('code'=>0,'msg'=>'获取成功','data'=>[
                    'goods_name' => $goods['goods_name'],
                    'pic_url' => $pic_url . '?v=' . time(),
                ] );
            $json_str = json_encode($json_arr,true);            
            exit($json_str);                    
        }
        $goods_pic_path = $this->saveTempImage($goods_pic_url);
        if (!$goods_pic_path){
            $json_arr = array('code'=>1,'msg'=>'获取商品海报失败：商品图片丢失');
            $json_str = json_encode($json_arr,true);            
            exit($json_str);
        }
        $goods_qrcode_dst = 'Public/qrcode/goods-qrcode-dst.jpg';
        $font_path = 'Public/fonts/st-heiti-light.ttc';
        
        $editor = Grafika::createEditor(GrafikaHelper::getSupportEditorLib());

        $editor->open($goods_qrcode, $goods_qrcode_dst);
        $editor->open($goods_pic, $goods_pic_path);
        
        //获取小程序码图片
        
        $wxapp_qrcode_file_res = $this->getQrcode1($pint['pint_id'], $user_id);


        if ($wxapp_qrcode_file_res['code'] == 1) {
            unlink($goods_pic_path);
            return [
                'code' => 1,
                'msg' => '获取商品海报失败：获取小程序码失败，' . $wxapp_qrcode_file_res['msg'],
            ];
        }
        $wxapp_qrcode_file_path = $wxapp_qrcode_file_res['file_path'];
        $editor->open($wxapp_qrcode, $wxapp_qrcode_file_path);

        $name_size = 30;
        $name_width = 670;
        //商品名称处理换行
        $name = $this->autowrap($name_size, 0, $font_path, $goods['goods_name'], $name_width, 2);
        //加商品名称
        $editor->text($goods_qrcode, $name, $name_size, 40, 750, new Color('#333333'), $font_path, 0);

        //裁剪商品图片
        //$editor->crop($goods_pic, 670, 670, 'smart');
        $editor->resizeFill($goods_pic, 670, 670);
        //附加商品图片
        $editor->blend($goods_qrcode, $goods_pic, 'normal', 1.0, 'top-left', 40, 40);

        //加商品价格
        $editor->text($goods_qrcode, '￥' . $goods['shop_price'], 45, 30, 910, new Color('#ff4544'), $font_path, 0);

        //加商城名称
        $editor->text($goods_qrcode, $store->name, 20, 40, 1170, new Color('#888888'), $font_path, 0);

        //调整小程序码图片
        $editor->resizeExactWidth($wxapp_qrcode, 240);
        //附加小程序码图片
        $editor->blend($goods_qrcode, $wxapp_qrcode, 'normal', 1.0, 'top-left', 470, 1040);
        
        //保存图片
        $editor->save($goods_qrcode, $goods_pic_save_path . $goods_pic_save_name, 'jpeg', 85);

        //删除临时图片
        unlink($goods_pic_path);
        unlink($wxapp_qrcode_file_path);    
        $json_arr = array('code'=>0,'msg'=>'获取成功','data'=>[
                    'goods_name' => $goods['goods_name'],
                    'pic_url' => $pic_url . '?v=' . time(),
                ] );
        $json_str = json_encode($json_arr,true);
        exit($json_str);
    }

    public function getQrcode($goods_id, $user_id,$pd="")
    {
        $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
        $config_value = unserialize($paymentPlugin['config_value']);
        $APPID=$config_value['appid'];
        $SECRET = $config_value['appsecret'];
        $api = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$APPID}&secret={$SECRET}";
        $res=$this->curl_get($api);
        $res = json_decode($res, true);

        if (empty($res['access_token'])) {
            return false;
        }

        $accessToken = $res['access_token'];
        $api = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
        $curl = new Curl();
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
        if($pd=='user'){
            $data = json_encode([
                'scene' => "uid:{$user_id}",
                'page' => "pages/index/index",
                'width' => 1280,
            ]);
        }elseif($pd=='yes'){
            $data = json_encode([
                'scene' => "store_id:{$goods_id},uid:{$user_id}",
                'page' => "pages/store/index",
                'width' => 240,
            ]);
        }elseif($pd=='store_id'){
            $data = json_encode([
                'scene' => "store_id:{$goods_id},bing_wx:1",
                'page' => "pages/store/index",
                'width' => 240,
            ]);
        }elseif($pd=='reguser'){
            $data = json_encode([
                'scene' => "uid:{$user_id}",
                'page' => "pages/login/login",
                'width' => 1280,
                ]);
        }else{
            $data = json_encode([
                'scene' => "gid:{$goods_id},uid:{$user_id}",
                'page' => 'pages/goods_details/goods_details',
                'width' => 240,
            ]);
        }

        $curl->post($api, $data);
        if (in_array('Content-Type: image/jpeg', $curl->response_headers)) {
            //返回图片
            $json_arr = array('code'=>0,'msg'=>'获取成功','file_path'=>$this->saveTempImageByContent($curl->response) );

            return 	$json_arr;
        } else {
            //返回文字
            $res = json_decode($curl->response, true);
            $json_arr = array('code'=>0,'msg'=>$res['errmsg']);

            return 	$json_arr;
        }
    }
	
    private function getQrcode1($pint_id, $user_id)
    {
        $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
        $config_value = unserialize($paymentPlugin['config_value']); 
        $APPID=$config_value['appid'];
        $SECRET = $config_value['appsecret'];       
        $api = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$APPID}&secret={$SECRET}";
        $res=$this->curl_get($api);
        $res = json_decode($res, true);
        
        if (empty($res['access_token'])) {
            
                return false;
        }
        
        $accessToken = $res['access_token'];
        $api = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
        $curl = new Curl();
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
        $data = json_encode([
            'scene' => "pid:{$pint_id},uid:{$user_id}",
            'page' => 'pages/pint/group/details',
            'width' => 240,
        ]);
        $curl->post($api, $data);
        if (in_array('Content-Type: image/jpeg', $curl->response_headers)) {
            //返回图片
 
            $json_arr = array('code'=>0,'msg'=>'获取成功','file_path'=>$this->saveTempImageByContent($curl->response) );
                        
            return  $json_arr;          
        } else {
            //返回文字
            $res = json_decode($curl->response, true);
            $json_arr = array('code'=>0,'msg'=>$res['errmsg']);
                        
            return  $json_arr;
        }
    }    
     //保存图片内容到临时文件
    private function saveTempImageByContent($content)
    {
        $save_path = QRCODE_PATH . '/image/' . md5(base64_encode($content)) . '.jpg';
        $fp = fopen($save_path, 'w');
        fwrite($fp, $content);
        fclose($fp);
        return $save_path;
    }
    //获取网络图片到临时目录
    public function saveTempImage($url)
    {
        $wdcp_patch = false;
        //$wdcp_patch_file = \Yii::$app->basePath . '/patch/wdcp.json';
        if (file_exists($wdcp_patch_file)) {
            $wdcp_patch = json_decode(file_get_contents($wdcp_patch_file), true);
            if ($wdcp_patch && in_array(\Yii::$app->request->hostName, $wdcp_patch)) {
                $wdcp_patch = true;
            } else {
                $wdcp_patch = false;
            }
        }
        if ($wdcp_patch)
            $url = str_replace('http://', 'https://', $url);

        if (!is_dir(QRCODE_PATH . '/image'))
            mkdir(QRCODE_PATH . '/image');

        $save_path = QRCODE_PATH . '/image/' . md5($url) . '.jpg';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $img = curl_exec($ch);
        curl_close($ch);
        $fp = fopen($save_path, 'w');
        fwrite($fp, $img);
        fclose($fp);
        return $save_path;
    }

	private function return_json($state,$msg,$data=array()){
		
			$json_arr = array('code'=>state,'msg'=>$msg,'data'=>$data);
			$json_str = json_encode($json_arr,true);			
			exit($json_str);
	}
	
	private function curl_get($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		$json_data = curl_exec($ch);
		curl_close($ch);
		return  $json_data;
	}
	
    /**
     * @param integer $fontsize 字体大小
     * @param integer $angle 角度
     * @param string $fontface 字体名称
     * @param string $string 字符串
     * @param integer $width 预设宽度
     */
    private function autowrap($fontsize, $angle, $fontface, $string, $width, $max_line = null)
    {
        // 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
        $content = "";
        // 将字符串拆分成一个个单字 保存到数组 letter 中
        $letter = [];
        for ($i = 0; $i < mb_strlen($string, 'UTF-8'); $i++) {
            $letter[] = mb_substr($string, $i, 1,'UTF-8');
        }
        $line_count = 0;
        foreach ($letter as $l) {
            $teststr = $content . " " . $l;
            $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
            // 判断拼接后的字符串是否超过预设的宽度
            if (($testbox[2] > $width) && ($content !== "")) {
                $line_count++;
                if ($max_line && $line_count >= $max_line) {
                    $content = mb_substr($content, 0, -1,'UTF-8') . "...";
                    break;
                }
                $content .= "\n";
            }
            $content .= $l;
        }
        return $content;
    }
    
    
}